美文网首页
3-5 如何在一个for语句中迭代多个可迭代对象

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

作者: 马小跳_ | 来源:发表于2017-12-11 09:21 被阅读0次

    实际案例:
    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)
    

    相关文章

      网友评论

          本文标题:3-5 如何在一个for语句中迭代多个可迭代对象

          本文链接:https://www.haomeiwen.com/subject/qqnbixtx.html