Ways to iterate over multiple iterables in a Python for statement

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 = []

Example 1: Parallel operation: implement parallel iteration of multiple lists in a for loop;

Solution: Use the built-in function zip to combine multiple iterable objects, returning a tuple for each iteration

Case: Iterate over 3 lists at the same time, and calculate the sum of the corresponding elements of each list;

Method 1: Directly use for loop reference

#弊端:只能支持引索操作:a1[],若操作对象是生成器,则不能实现;
for i in range(5):
    t = a1[i] + a2[i] + a3[i]
    a4.append(t)

print(a4)
#输出:[84, 67, 85, 88, 82]

Method 2: Use the built-in function zip()

for x, y, z in zip(a1, a2, a3):
    a4.append(x + y + z)

print(a4)
#输出:[44, 72, 73, 94, 130]

**Example 2:** Chuanxing operation: realize the Chuanxing iteration of multiple lists in a for loop;

**Scenario:** Use the standard library itertools.chain, which enables multiple iterative objects to be linked

Scenario one :

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']

Scenario two:

for x in chain(b1, b2):
    print(x)
#输出:1 2 3 4 a b c

**Case:** Iterate over 4 lists to filter out the target data (numbers greater than 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)

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/123908093