How do I eterate multiple iterables at the same time?

Asked 2 years ago, Updated 2 years ago, 92 views

When there are two iterables, each element is paired

foo = (1,2,3)
bar = (4,5,6)

for (f,b) in some_iterator(foo, bar):
    print "f: ", f ,"; b: ", b

Use this code to make a result

f: 1; b: 4
f: 2; b: 5
f: 3; b: 6

I want to receive it like this.

I know how to access the index like this, but I don't think it's a Python code. Please tell me another way

for i in xrange(len(foo)):
    print "f: ",foo[i] ,"; b: ", b[i]

python iterator parallel-processing

2022-09-21 19:42

1 Answers

for f, b in zip(foo, bar):
    print(f, b)

If you write in , repeat statements end based on foo or bar which is smaller.

In python2, zip() returns a list that stores the tuple. Therefore, if foo and bar are too large, it is inefficient to create a temporary object that is too large In this case, change the zip to itertools.izip or itertools.izip_longest and write itterator, not list.

Example:

import itertools
for f,b in itertools.izip(foo,bar):
    print(f,b)
for f,b in itertools.izip_longest(foo,bar):
    print(f,b)

If you use itertools.izip(), the repeat statement ends based on foo or bar whichever is shorter. If you use itertools.izip_longest(), the repeat statement ends based on foo or bar whichever is longer. If one side is shorter, None is included in the element of the tuple.

In python3, zip() returns the e-later of the tuple, as in itertools.izip in python2. If you want to receive a list like Python2's zip(), please write list(foo, bar).


2022-09-21 19:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.