Python中for循环如何同时迭代多个对象

同时迭代多个对象分为两种情况

  • 并行迭代
    情景假设:某个班级的数学成绩,英语成绩,语文成绩分别存在一个列表中,求每个学生的总分
    对于并行迭代可以使用zip函数
# 并行
chinese = [randint(60, 100) for _ in range(40)]
math = [randint(60, 100) for _ in range(40)]
english = [randint(60, 100) for _ in range(40)]
total = []
for x, y, z in zip(chinese, math, english):
    total.append(x + y + z)
  • 串行迭代
    情景假设:若干个班级的数学成绩存在多个列表中,求分数高于80分的人
    对于串行迭代可以使用itertools.chain函数
# 串行
class1 = [randint(60, 100) for _ in range(40)]
class2 = [randint(60, 100) for _ in range(40)]
class3 = [randint(60, 100) for _ in range(40)]
l = filter(lambda x: x >= 80, chain(class1, class2, class3))

你可能感兴趣的:(Python中for循环如何同时迭代多个对象)