¿Cómo puedo recorrer una lista de dos en dos? [duplicar]


Posible Duplicado:
¿Cuál es la forma más "pitónica"de iterar sobre una lista en trozos?

Quiero recorrer una lista de Python y procesar 2 elementos de lista a la vez. Algo como esto en otro idioma:

for(int i = 0; i < list.length(); i+=2)
{
   // do something with list[i] and list[i + 1]
}

¿Cuál es la mejor manera de lograr esto?

Author: martineau, 2010-06-07

7 answers

Puede usar para in range con un tamaño de paso de 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

Nota: Use xrange en Python 2 en lugar de range porque es más eficiente ya que genera un objeto iterable, y no toda la lista.

 270
Author: Brian R. Bondy,
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-05-11 10:48:32

También puede usar esta sintaxis (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
    print i,
# prints 1 3 5 7 9

for i in mylist[1::2]:
    print i,
# prints 2 4 6 8 10

Donde el primer dígito es el índice inicial (por defecto al principio de la lista o 0), el segundo es el índice de corte final (por defecto al final de la lista), y el tercer dígito es el desplazamiento o paso.

 58
Author: jathanism,
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
2010-06-07 14:20:21

Si está utilizando Python 2.6 o posterior, puede usar la receta del mero de la itertools módulo:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Llama así:

for item1, item2 in grouper(2, l):
    # Do something with item1 and item2

Tenga en cuenta que en Python 3.x debe usar zip_longest en lugar de izip_longest.

 38
Author: Mark Byers,
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
2010-06-07 14:31:03

Lo más simple en mi opinión es solo esto:

it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
    print x, y

No hay importaciones adicionales ni nada. Y muy elegante, en mi opinión.

 38
Author: carl,
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
2012-12-06 01:35:39
nums = range(10)
for i in range(0, len(nums)-1, 2):
    print nums[i]

Un poco sucio, pero funciona.

 4
Author: Ishpeck,
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
2010-06-07 14:21:56

Esto podría no ser tan rápido como la solución izip_longest (en realidad no la probé), pero funcionará con python

from itertools import imap

def grouper(n, iterable):
    "grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
    args = [iter(iterable)] * n

    return imap(None, *args)

Si necesita ir antes de la versión 2.3, puede sustituir el mapa integrado por imap. La desventaja es que no proporciona la capacidad de personalizar el valor de relleno.

 2
Author: lambacck,
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-09-09 12:05:09

Si tienes control sobre la estructura de la lista, lo más pitónico que puedes hacer probablemente sería cambiarla de:

l=[1,2,3,4]

A:

l=[(1,2),(3,4)]

Entonces, tu bucle sería:

for i,j in l:
    print i, j
 0
Author: Jorenko,
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
2010-06-07 14:06:41