例子:多條件迭代
for abc in ['The number is '+str(x)+'!!!!!' for x in range(5) if x %2==0]:
print abc
結(jié)果:
The number is 0!!!!!
The number is 2!!!!!
The number is 4!!!!!
例子:字典迭代
dic= {'No1':'Janme','No2':'Lemon'}
for no, name in dic.iteritems():
print no,'is ', name
結(jié)果:
No1 is Janme
No2 is Lemon
例子:字符串中的一部分進(jìn)行迭代
['the number' + str(x) + 'is best!' for x in range(4)]
結(jié)果:
['the number0is best!', 'the number1is best!', 'the number2is best!', 'the number3is best!']
例子:把list中的所有元素大寫改成小寫
L = ['SAHPE','WHAT','SALT']
[s.lower() for s in L]
結(jié)果:
['sahpe', 'what', 'salt']
如果把[]換成()能犯,則上面的列表將變成生成器疯搅,累死yield,這樣占用內(nèi)存更小。