3-5 如何在一个for语句中迭代多个可迭代对象

实际案例:
1.某班学生期末考试成绩,语文,数学,英语分别存储在三个列表中,
同时迭代三个列表,计算每个学生的总分(并行)

2.某年级有四个班,某次考试每班英语成绩分别存储在4个列表中,
依次迭代每个列表,统计全年级成绩高于90分的人数(串行)

解决方案:
并行:使用内置函数zip,它能将多个可迭代对象合并,每次迭代返回一个元组
串行:使用标准库中的itertools.chain,它能将多个可迭代对象连接

方案一:

zip(iter1 [,iter2 [...]]) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
from random import randint
count = 30  # 班级人数
chinese = [randint(50,100) for _ in range(count)]
math = [randint(50,100) for _ in range(count)]
english = [randint(50,100) for _ in range(count)]


# 方式一:索引  局限性:不适用与迭代器与生成器
for i in range(count):
    print(i,chinese[i],math[i],english[i],)


# 方式二:zip和拆包
for c,m,e in zip(chinese,math,english):
    print(c,m,e)

方案二:

chain(*iterables) --> chain object

Return a chain object whose .__next__() method returns elements from the
first iterable until it is exhausted, then elements from the next
iterable, until all of the iterables are exhausted.
from itertools import chain

# 随机生成4个班的英语成绩
cls1 = [randint(60,100) for _ in range(30)]
cls2 = [randint(60,100) for _ in range(30)]
cls3 = [randint(60,100) for _ in range(30)]

count = 0

for x in chain(cls1,cls2,cls3):
    if x >= 90:
        count += 1
print(count)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容