¿Cómo iterar a través de dos listas en paralelo?
Tengo dos iterables en Python, y quiero repasarlos en pares:
foo = (1, 2, 3)
bar = (4, 5, 6)
for (f, b) in some_iterator(foo, bar):
print "f: ", f, "; b: ", b
Debería resultar en:
f: 1; b: 4
f: 2; b: 5
f: 3; b: 6
Una forma de hacerlo es iterar sobre los índices:
for i in xrange(len(foo)):
print "f: ", foo[i], "; b: ", b[i]
Pero eso me parece algo impitónico. ¿Hay una mejor manera de hacerlo?
7 answers
for f, b in zip(foo, bar):
print(f, b)
zip
se detiene cuando el más corto de foo
o bar
se detiene.
zip
devuelve una lista de tuplas. Esto está bien cuando foo
y bar
no son masivos. Si
ambos son masivos entonces la formación zip(foo,bar)
es un innecesariamente masivo
variable temporal, y debe sustituirse por itertools.izip
o
itertools.izip_longest
, que devuelve un iterador en lugar de una lista.
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
se detiene cuando se agota foo
o bar
.
izip_longest
se detiene cuando foo
y bar
están agotados.
Cuando se agotan los iteradores más cortos, izip_longest
produce una tupla con None
en la posición correspondiente a ese iterador. También puede establecer un fillvalue
diferente además de None
si lo desea. Vea aquí la historia completa .
zip
devuelve un iterador de tuplas, como itertools.izip
en Python2. Para obtener una lista
de tuplas, use list(zip(foo, bar))
. Y zip hasta que ambos iteradores son
agotado, lo haría utilizar
itertools.zip_longest .
Tenga en cuenta también que zip
y su zip
-como brethen puede aceptar un número arbitrario de iterables como argumentos. Por ejemplo,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
Impresiones
1 red manchego
2 blue stilton
3 green brie
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-11 17:13:48
Desea la función zip
.
for (f,b) in zip(foo, bar):
print "f: ", f ,"; b: ", b
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-02 21:27:53
El builtin zip
hace exactamente lo que quieres. Si desea lo mismo sobre iterables en lugar de listas, podría mirar itertools.izip que hace lo mismo pero da resultados uno a la vez.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-02 21:28:11
Lo que estás buscando se llama zip
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-02 21:28:02
Debe usar la función ' zip'. Aquí hay un ejemplo de cómo su propia función zip puede verse como
def custom_zip(seq1, seq2):
it1 = iter(seq1)
it2 = iter(seq2)
while True:
yield next(it1), next(it2)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-23 11:09:20
La función Zip resuelve el problema
Docs: Función de biblioteca ZIP
OBJETIVO: Poner la salida lado a lado Problema:
#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"
Salida:
revisión1
revisión2
revisión3
date1
date2
date3
Solución:
for val1, val2 in zip(value1,value2):
print (val1.text+':'+val2.text)
print "\n"
Salida:
revisión 1: date1
review2:date2
revisión 3: date3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-25 08:16:30