实际案例:
- 某班学生期末考试成绩,语文、数学、英语分别存储在3个列表中,同时迭代三个列
表,计算每个学生的总分.(并行) - 某年级有4个班,某次考试每班英语成绩分别存储在4个列表中,依次迭代每个列表,统计全学年成绩高于90分的人.(串行)
首先创建测试数据:
from random import randint
chinese = [randint(60,100) for _ in range(40)]
math= [randint(60,100) for _ in range(40)]
english = [randint(60,100) for _ in range(40)]
解决方式:
- 并行:使用内置函数zip,它能将多个可迭代对象合并,每次迭代返回一个元组
- 串行:使用标准库中的itertools.chain,它能将多个可迭代对象连接
并行:
total = []
for c,m,e in zip(chinese,math,english):
total.append(c+m+e)
串行:
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)]
from itertools import chain
count = 0
for i in chain(e1,e2,e3,e4):
if i > 90:
count+=1
网友评论