并行
zip函数将多个可迭代对象合并,每次迭代返回一个元祖
from random import randint
total = []
chinese = [randint(60, 100) for _ in range(40)]
math = [randint(60, 100) for _ in range(40)]
english = [randint(60, 100) for _ in range(40)]
for c, m, e in zip(chinese, math, english):
total.append(c + m + e)
for x in total:
print(x)
串行
(某年级有四个班,每个班的英文成绩记录在四个表中,一次迭代每个列表, 找到全部成绩大于90 的学生)
使用标准库中的itertool.chain,它将多个可迭代对象连接
from random import randint
from itertools import chain
e1 = [randint(60, 100) for _ in range(40)]
e2 = [randint(60, 100) for _ in range(40)]
e3 = [randint(60, 100) for _ in range(40)]
e4 = [randint(60, 100) for _ in range(40)]
total = 0
for x in chain(e1, e2, e3, e4):
if x >= 90:
total += 1
print(total)