使用for语句来迭代多个可迭代对象

并行

zip函数将多个可迭代对象合并,每次迭代返回一个元祖

from random import randint
total = []
chinese = [randint(60, 100) for _ in range(40)]
math = [randint(60, 100) for _ in range(40)]
english = [randint(60, 100) for _ in range(40)]
for c, m, e in zip(chinese, math, english):
    total.append(c + m + e)
for x in total:
    print(x)

串行

(某年级有四个班,每个班的英文成绩记录在四个表中,一次迭代每个列表, 找到全部成绩大于90 的学生)

使用标准库中的itertool.chain,它将多个可迭代对象连接

from random import randint
from itertools import chain
e1 = [randint(60, 100) for _ in range(40)]
e2 = [randint(60, 100) for _ in range(40)]
e3 = [randint(60, 100) for _ in range(40)]
e4 = [randint(60, 100) for _ in range(40)]
total = 0
for x in chain(e1, e2, e3, e4):
    if x >= 90:
        total += 1
print(total)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值