迭代是循环的另一种说法
并行迭代
>>> names = ['anne', 'beth', 'george', 'damon']
>>> ages = [12,45,32,102]
>>> for i in range(len(names)):
print(names[i],'is', ages[i],'years old')
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
#另一种方法:其中zip函数可以用于任意多的序列,将序列“压缩”在一起,然后返回一个元组列表
>>> for names,ages in zip(names, ages):
print(names,'is',ages, 'years old')
按索引迭代
for index, string in enumerate(strings): #其中enumerate(枚举,列举)函数可以在提供索引的地方返回迭代索引和值
if 'xxx' in string:
string[index] = '[censored]'
循环中的else语句
for i in range(99,81,-1):
root = sqrt(i)
if root == int(root):
print(i)
break
else:
print("don't")
don't
如上代码可以看到,循环for/while是可以使用else语句的,即循环完成后将会继续执行else语句中的内容
列表推导式—-轻量级循环
利用其它列表创建新列表的方法
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
#得到首字母相同的男孩女孩
>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b+'+'+g for b in girls for g in boys if b[0]==g[0]]
['alice+arnold', 'bernice+bob', 'clarice+chris']