问题13:如何在for语句中迭代多个可迭代的对象
from random import randint a1 = [randint(10, 50) for _ in range(5)] a2 = [randint(10, 50) for _ in range(5)] a3 = [randint(10, 50) for _ in range(5)] a4 = []
例一:并行操作:在一个for循环中实现多个列表的并行迭代;
方案:使用内置函数zip,将多个迭代对象合并,每次迭代返回一个元组
案例:对3个列表同时迭代,计算各列表对应元素的和;
#方法一:直接用for循环引用 #弊端:只能支持引索操作:a1[],若操作对象是生成器,则不能实现; for i in range(5): t = a1[i] + a2[i] + a3[i] a4.append(t) print(a4) #输出:[84, 67, 85, 88, 82] #方法二:用内置函数zip() for x, y, z in zip(a1, a2, a3): a4.append(x + y + z) print(a4) #输出:[44, 72, 73, 94, 130]
例二:川行操作:在一个for循环中实现多个列表的川行迭代;
方案:使用标准库itertools.chain,它能使多个迭代对象连接
itertools.chain的使用,也可参考:Python:itertools库的使用
场景一:
from itertools import chain b1 = [1, 2, 3, 4] b2 = ['a', 'b', 'c'] b3 = list(chain(b1, b2)) print(b3) #输出:[1, 2, 3, 4, 'a', 'b', 'c']
场景二: for x in chain(b1, b2): print(x) #输出:1 2 3 4 a b c
案例:对4个列表进行迭代操作,筛选出目标数据(大于40的个数):
from itertools import chain from random import randint a1 = [randint(10, 50) for _ in range(40)] a2 = [randint(10, 50) for _ in range(41)] a3 = [randint(10, 50) for _ in range(42)] a4 = [randint(10, 50) for _ in range(43)] count = 0 for x in chain(a1, a2, a3, a4): if x >=40: count += 1 print(count)