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

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

问题举例

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

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

解决思路

(1)使用内置函数zip,它能将多个可迭代对象合并,每次迭代返回一个元组(并行)

(2)使用标准库中itertools.chain,它能将多个可迭代对象连接(串行)

代码(并行)

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)]

res1 = []
for s1, s2, s3 in zip(chinese, math, english):
    res1.append(s1 + s2 + s3)

print(res1)

res2 = [sum(s) for s in zip(chinese, math, english)]
res3 = list(map(sum, zip(chinese, math, english)))
res4 = list(map(lambda s1, s2, s3: s1 + s2 + s3, chinese, math, english))
print(res2)
print(res3)
print(res4)

print("
map and zip do same function")
list1 = list(map(lambda *args: args, chinese, math, english))
list2 = list(zip(chinese, math, english))
print(list1 == list2)

代码(串行)

from random import randint
from itertools import chain

c1 = [randint(60, 100) for _ in range(20)]
c2 = [randint(60, 100) for _ in range(20)]
c3 = [randint(60, 100) for _ in range(23)]
c4 = [randint(60, 100) for _ in range(25)]
print(c1)
print(c2)
print(c3)
print(c4)
nums = len([x for x in chain(c1, c2, c3, c4) if x > 90])
print(nums)

参考资料:python3实用编程技巧进阶

原文地址:https://www.cnblogs.com/marton/p/10772186.html