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 : In a for The parallel iteration of multiple lists is realized in the loop ;
programme : Use built-in functions zip, Merge multiple iteration objects , Each iteration returns a tuple
case : yes 3 Multiple lists iterate simultaneously , Calculate the sum of the corresponding elements of each list ;
<> Method 1 : Direct use for Circular reference
# malpractice : Only index operation is supported :a1[], If the generator object is an action , Cannot be achieved ; for i in range(5): t = a1[i] + a2[i] +
a3[i] a4.append(t) print(a4) # output :[84, 67, 85, 88, 82]
<> Method 2 : Using built-in functions zip()
for x, y, z in zip(a1, a2, a3): a4.append(x + y + z) print(a4) # output :[44, 72,
73, 94, 130]
** Example 2 :** Sichuan operation : In a for Iteration of multiple lists in the loop ;
** programme :** Use standard library itertools.chain, It can connect multiple iterative objects
Scene 1 :
from itertools import chain b1 = [1, 2, 3, 4] b2 = ['a', 'b', 'c'] b3 =
list(chain(b1, b2)) print(b3) # output :[1, 2, 3, 4, 'a', 'b', 'c']
Scene 2 :
for x in chain(b1, b2): print(x) # output :1 2 3 4 a b c
** case :** yes 4 Iterate through a list , Filter out target data ( greater than 40 Number of ):
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)
Technology
Daily Recommendation