其他综合表达式
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> (x*x for x in range(10))
<generator object <genexpr> at 0x1034116d0>
>>> {x*x for x in range(10)}
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
>>> {x: x*x for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
字典--内容与创建
>>> D = {'info':{42:1,type(''):2},'spam':[]}
>>> D
{'spam': [], 'info': {42: 1, <class 'str'>: 2}}
>>> D = dict(name='bob',age=45,job=('mrg','dev'))
>>> D
{'job': ('mrg', 'dev'), 'age': 45, 'name': 'bob'}
>>> D = dict(zip('abc',[1,2,3]))
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> D = {c.upper():ord(c) for c in 'spam'}
>>> D
{'P': 112, 'S': 115, 'M': 109, 'A': 97}
>>> {'spam':2,'egg':3}
{'spam': 2, 'egg': 3}
字典--运算
>>> D.keys()
dict_keys(['P', 'S', 'M', 'A'])
>>> D.values()
dict_values([112, 115, 109, 97])
>>> D.items()
dict_items([('P', 112), ('S', 115), ('M', 109), ('A', 97)])
>>> D.clear()
>>> D
{}
>>> D = {c.upper():ord(c) for c in 'spam'}
>>> D
{'P': 112, 'S': 115, 'M': 109, 'A': 97}
>>> D.copy()
{'S': 115, 'P': 112, 'M': 109, 'A': 97}
>>> D2 = {'spam':2,'egg':3}
>>> D.update(D2)
>>> D
{'egg': 3, 'M': 109, 'S': 115, 'spam': 2, 'P': 112, 'A': 97}
>>> D.get('S')
115
>>> D.setdefault('S')
115
>>> D.popitem()
('egg', 3)
>>> D
{'M': 109, 'S': 115, 'spam': 2, 'P': 112, 'A': 97}
>>> D.pop('M')
109
>>> D
{'S': 115, 'spam': 2, 'P': 112, 'A': 97}
>>> D.pop('M') #如果K存在则删除。否则,存在默认值则返回一个默认值,不存在则发送KeyError异常。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'M'
>>> dict.fromkeys(I[,value])#该方法创建一个新字典,字典键值来自迭代I,并将每个集合的值设置为value(默认为None)。可随时调用D的一个实例或类型名dict。
k in D
for k in D
元组--内容与创建
>>> ()
()
>>> (0,)
(0,)
>>> (0,1,2,3)
(0, 1, 2, 3)
>>> T = ('spam',(42,'egg'))
>>> T
('spam', (42, 'egg'))
>>> T = tuple('spam')
>>> T
('s', 'p', 'a', 'm')
元祖--运算
>>> T.index('p')#T.index(X[,i[,j])
1
>>> T.count('a')
1
>>> T.count('q')
0