如何在一个for语句中迭代多个对象
总结:
并行迭代使用zip(l1, l2, l3)
每次迭代从3个列表里各取一个数据
串行迭代使用itertools.chain(l1, l2, l3)
相当于把3个里边拼接成了一个列表再迭代
并行迭代:使用zip 某班4个人各科成绩的迭代
from random import randint
l1 = ['jwang', 'Tom', 'Jerry', 'Liming']
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(4)]
print(l1)
print(l2)
print(l3)
print(l4)
for name, math, english, physics in zip(l1, l2, l3, l4):
print("name:%s, math:%s, english:%s, physics:%s" % (name, math, english, physics))
output:
['jwang', 'Tom', 'Jerry', 'Liming']
[64, 69, 94, 93]
[81, 89, 64, 80]
[69, 94, 81, 62]
name:jwang, math:64, english:81, physics:69
name:Tom, math:69, english:89, physics:94
name:Jerry, math:94, english:64, physics:81
name:Liming, math:93, english:80, physics:62
如果列表长度不一样也能迭代
from random import randint
l1 = ['jwang', 'Tom', 'Jerry', 'Liming']
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(3)]
print(l1)
print(l2)
print(l3)
print(l4)
for name, math, english, physics in zip(l1, l2, l3, l4):
print("name:%s, math:%s, english:%s, physics:%s" % (name, math, english, physics))
output:
['jwang', 'Tom', 'Jerry', 'Liming']
[92, 66, 91, 75]
[72, 92, 100, 77]
[71, 67, 98]
name:jwang, math:92, english:72, physics:71
name:Tom, math:66, english:92, physics:67
name:Jerry, math:91, english:100, physics:98
串性迭代 使用chain
for x in chain([1, 2, 3, 4],['a', 'b', 'c']):
print(x)
output:
1
2
3
4
a
b
c
4个班 每个班的英语成绩各存一个列表,统计全学年成绩高于90的人数
from itertools import chain
l1 = [randint(60, 100) for x in range(4)]
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(3)]
print(l1)
print(l2)
print(l3)
print(l4)
count = 0
for x in chain(l1, l2, l3, l4):
if x>90:
count += 1
print(count)
output:
[66, 94, 66, 73]
[98, 90, 90, 60]
[69, 83, 75, 61]
[71, 83, 68]
2