Jak iterować przez dwie listy równolegle?

Mam dwa iterable w Pythonie i chcę je przejrzeć parami:

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

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

Powinno wynikać:

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

jednym ze sposobów jest iteracja indeksów:

for i in xrange(len(foo)):
    print "f: ", foo[i], "; b: ", b[i]
Ale to wydaje mi się trochę niepytoniczne. Jest na to lepszy sposób?
Author: martineau, 2009-11-03

7 answers

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

zip zatrzymuje się, gdy krótszy z foo lub bar zatrzymuje się.

W Python 2, zip zwraca listę krotek. Jest to w porządku, gdy foo i bar nie są masywne. Jeśli oba są masywne, a formowanie {[10] } jest niepotrzebnie masywnym zmienną tymczasową i powinna być zastąpiona przez itertools.izip lub itertools.izip_longest, który zwraca iterator zamiast listy.

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)

izip zatrzymuje się, gdy foo lub bar jest wyczerpany. izip_longest zatrzymuje się, gdy zarówno foo jak i bar są wyczerpani. Gdy krótsze Iteratory są wyczerpane, izip_longest daje krotkę z None w pozycji odpowiadającej temu iteratorowi. Możesz również ustawić inny fillvalue oprócz None, jeśli chcesz. Zobacz tutaj pełna historia .

W Python 3, zip zwraca iterator krotek, jak itertools.izip W Python2. Aby otrzymać listę krotek, użyj list(zip(foo, bar)). I zip, aż oba Iteratory będą wyczerpany, użycie itertools.zip_longest .


Zauważ również, że zip i jego zip-podobne do zip mogą przyjmować dowolną liczbę iterabli jako argumenty. Na przykład,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                              ['red', 'blue', 'green']):
    print('{} {} {}'.format(num, color, cheese))

Druki

1 red manchego
2 blue stilton
3 green brie
 912
Author: unutbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-11 17:13:48

Chcesz zip funkcji.

for (f,b) in zip(foo, bar):
    print "f: ", f ,"; b: ", b
 41
Author: Karl Guertin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-02 21:27:53

Wbudowany zip robi dokładnie to, co chcesz. Jeśli chcesz to samo nad iterabami zamiast List, możesz spojrzeć na itertools.izip, który robi to samo, ale daje wyniki po kolei.

 12
Author: robince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-02 21:28:11

To, czego szukasz, nazywa się zip.

 9
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-02 21:28:02

Powinieneś użyć funkcji " zip ". Oto przykład, jak może wyglądać Twoja własna funkcja zip

def custom_zip(seq1, seq2):
    it1 = iter(seq1)
    it2 = iter(seq2)
    while True:
        yield next(it1), next(it2)
 5
Author: Vlad Bezden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-23 11:09:20

Funkcja Zip rozwiązuje problem
Docs: funkcja biblioteki ZIP

Cel: umieszczenie wyjścia obok siebie Problem:

#value1 is a list
value1 = driver.find_elements_by_class_name("review-text")
#value2 is a list
value2 = driver.find_elements_by_class_name("review-date")

for val1 in value1:
    print(val1.text)
    print "\n"
for val2 in value2:
    print(val2.text)
    print "\n"

Wyjście:
recenzja1
review2
review3
date1
date2
date3

Rozwiązanie:

for val1, val2 in zip(value1,value2):
    print (val1.text+':'+val2.text)
    print "\n"

Wyjście:
review1: date1
review2: date2
review3: date3

 3
Author: Manojit Ballav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 06:39:19
def ncustom_zip(seq1,seq2,max_length):
        length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
        for i in range(length):
                x= seq1[i] if len(seq1)>i else None  
                y= seq2[i] if len(seq2)>i else None
                yield x,y


l=[12,2,3,9]
p=[89,8,92,5,7]

for i,j in ncustom_zip(l,p,True):
        print i,j
for i,j in ncustom_zip(l,p,False):
        print i,j
 -2
Author: Sagar T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-25 08:16:30