列表解析式
没有列表解析式的情况下:
x = [] for i in (1,2,3): x.append(i) print x
返回: [1, 2, 3]
|
使用列表解析式的实现:
>>> x = [i for i in (1,2,3)] >>> x [1, 2, 3]
|
x = [word.capitalize() for line in ('hello world?','world!','or not') for word in line.split() if not word.startswith('or')]
print x
['Hello', 'World?', 'World!', 'Not']
|
字典解析式
In [18]: {x:x.upper() for x in ['hello',' world']} Out[18]: {' world': ' WORLD', 'hello': 'HELLO'}
|
In [19]: {x.upper() for x in ['hello','world']} Out[19]: {'HELLO', 'WORLD'}
|
In [24]: word = 'letter'
In [25]: letter_counts = {letter: word.count(letter) for letter in set(word)}
In [26]: letter_counts Out[26]: {'e': 2, 'l': 1, 'r': 1, 't': 2}
|
集合解析式
In [24]: a= {x.upper() for x in ['hello','world']}
In [25]: print a set(['WORLD', 'HELLO'])
|
enumerate
enumerate(sequence, start=0)
返回一个可迭代enumerate对象,它生成一个元组序列,
不用 enumerate的写法:
i = 0 mylist = ['first','two','three'] while i < len(mylist): print("Item %d: %s:" % (i,mylist[i])) i +=1
Item 0: first: Item 1: two: Item 2: three:
|
enumerate写法
mylist = ['first','two','three']
for i,item in enumerate(mylist): print("Item %d: %s" % (i,item))
Item 0: first Item 1: two Item 2: three
|
item为列表中的元素
。