Python-如何在一个for循环中迭代多个可迭代对象?

案例:

  1. 某班学生期末考试成绩,语文、数学、英语分别存储在3个列表中,同时迭代三个列表。,计算每个学生的总分(并行)
  2. 某年级有4个班,某次英语成绩分别记录在4个列表中,依次迭代每个列表,统计全年级高于90分人数

如何解决?

  1. 方法1:通过索引

#!/usr/bin/python3

from random import randint


def get_result(chinese, math, english):
    total = []
    # 循环索引进行取值,毕竟列表等长且成绩对应
    for index in range(len(chinese)):
        total.append(chinese[index] + math[index] + english[index])
    return total

if __name__ == '__main__':
    # 生成 3 个成绩列表
    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 = get_result(chinese, math, english)
    
    for x in total:
        print(x)

      方法2: 通过zip函数,同时迭代3个列表

#!/usr/bin/python3

from random import randint


def get_result(chinese, math, english):
    total = []
    # 通过zip函数进行迭代,实现同时迭代 3 个对象
    for c, m, e in zip(chinese, math, english):
        print(c, m, e)
        total.append(c + m + e)
    return total

if __name__ == '__main__':
    # 生成 3 个成绩列表
    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 = get_result(chinese, math, english)
    
    for x in total:
        print(x)

  2方法1: 通过 itertools中 chain方法

#!/usr/bin/python3

from random import randint
from itertools import chain


def get_result(e1, e2, e3):
    # 通过chain函数进行连续窜行迭代3个列表
    for i in chain(e1, e2, e3):
        print(i)

if __name__ == '__main__':
    # 生成 3 个班成绩单,1班36人,2班43人,3班40人
    e1 = [randint(60, 100) for _ in range(36)]
    e2 = [randint(60, 100) for _ in range(43)]
    e3 = [randint(60, 100) for _ in range(40)]
    
    # 依次打印成绩
    get_result(e1, e2, e3)
posted @ 2017-07-29 00:21  梦_鱼  阅读(3507)  评论(0编辑  收藏  举报