要求:
-
(并行迭代)某班学生期末考试成绩语文、数学、英语分别存储在3个列表中,同时迭代3个列表,计算每个学生的总分。
-
(串行迭代)某年级有4个班,某次考试每班英语成绩分别存储在4个列表中,依次迭代每个列表,统计全年级成绩高于90分人数。
解决方案:
-
(并行迭代)使用内置函数
zip()
,它可以将多个可迭代对象合并,每次迭代返回一个元组。 -
(串行迭代)使用标准库中的
itertools.chain()
函数,它可以将多个可迭代对象连接起来,成为一个可迭代对象。
- 对于
zip()
和map()
:
>>> list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> list(map(lambda *args: args, [1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
可以看到,结果一致。map()
函数可以实现zip()
函数的功能。
- 对于
itertools.chain()
函数:
itertools.chain(*iterables)
创建一个迭代器,它首先返回第一个可迭代对象中所有元素,接着返回下一个可迭代对象中所有元素,直到耗尽所有可迭代对象中的元素。可将多个序列处理为单个序列。
- 并行迭代方案示例:
from random import randint
chinese = [randint(60, 100) for _ in range(20)]
math = [randint(60, 100) for _ in range(20)]
english = [randint(60, 100) for _ in range(20)]
score = [sum(s) for s in zip(chinese, math, english)]
# score = list(map(lambda s1,s2,s3: s1+s2+s3, chinese, math, english)) #使用map()也可实现并行迭代
print(score)
[239, 235, 217, 237, 254, 254, 240, 264, 244, 233, 225, 238, 221, 236, 262, 253, 245, 246, 230, 262] #结果
- 串行迭代方案示例:
from random import randint
from itertools import chain
c1 = [randint(60, 100) for _ in range(20)]
c2 = [randint(60, 100) for _ in range(15)]
c3 = [randint(60, 100) for _ in range(25)]
c4 = [randint(60, 100) for _ in range(18)]
count = len([x for x in chain(c1, c2, c3, c4) if x > 90])
print(count)
13 #结果