例子:多条件迭代
for abc in ['The number is '+str(x)+'!!!!!' for x in range(5) if x %2==0]:
print abc
结果:
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
结果:
No1 is Janme
No2 is Lemon
例子:字符串中的一部分进行迭代
['the number' + str(x) + 'is best!' for x in range(4)]
结果:
['the number0is best!', 'the number1is best!', 'the number2is best!', 'the number3is best!']
例子:把list中的所有元素大写改成小写
L = ['SAHPE','WHAT','SALT']
[s.lower() for s in L]
结果:
['sahpe', 'what', 'salt']
如果把[]换成(),则上面的列表将变成生成器,累死yield,这样占用内存更小。
网友评论