get()函数用法
>>> name = 'yes'
>>> d = {'key1':'123','key2':123}
>>> d[name] = 'kayson'
>>> d[0]= name
>>> d
{0: 'yes', 'key2': 123, 'key1': '123', 'yes': 'kayson'}
>>> print d
{0: 'yes', 'key2': 123, 'key1': '123', 'yes': 'kayson'}
>>> help(d.get)
Help on built-in function get:
get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
'''解释
D.get(k[,d]) =====> D.get(k) or D.get(k,d)
k为字典中key,d为返回值(即字典中key所对应的值)
如果key不存在,则默认返回None
如果key存在,则返回字典中key所对应的值
'''
# 示例
>>> D={'k':'d'}
>>> D
{'k': 'd'}
>>> D.get('k')
'd'
#字典中没有yes这个key字段,则返回None(默认值)
#字典中没有yes这个key字段,但定义默认值为NO EXITS,则返回NO EXITS值
>>> D.get('yes','NO EXITS')
'NO EXITS'
'''
not X的理解
if X is False;then True;else False #这里的X个人理解为not X
在python中
None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
即:
not None == not False == not '' == not 0 == not [] == not {} == not ()
####代码示例
>>> x = []
>>> not x is False
True
'''
>>>
>>> print D.get('yes')
None
>>> state = D.get('yes') # 即 state = None
>>> if not state:
... print 'the value is none.'
>>>
>>>
>>> D.get('yes','NO EXITS')
'NO EXITS'
>>> state1 = D.get('yes','NO EXITS') # 即 state1 = NO EXITS
>>> if not state1:
... print 'the value is %s.' % state1
阅读(7314) | 评论(0) | 转发(0) |