python: itera un rango específico en una lista


Digamos que tengo una lista:

listOfStuff =([a,b], [c,d], [e,f], [f,g])

Lo que quiero hacer es recorrer los 2 componentes centrales de una manera similar al siguiente código:

for item in listOfStuff(range(2,3))
   print item

El resultado final debe ser:

[c,d]
[e,f]

Este código actualmente no funciona, pero espero que pueda entender lo que estoy tratando de hacer.

Author: Steven Bluen, 2011-03-31

4 answers

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

Tienes que iterar sobre una porción de tu tupla. El 1 es el primer elemento que necesita y 3 (en realidad 2+1) es el primer elemento que no necesita.

Los elementos de una lista se numeran desde 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] toma los elementos 1 y 2.

 36
Author: eumiro,
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
2011-03-31 14:48:44

Una forma más eficiente de memoria para iterar sobre una porción de una lista sería usar islice() desde el módulo itertools:

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print item

# ['c', 'd']
# ['e', 'f']

Sin embargo, esto puede ser relativamente ineficiente en términos de rendimiento si el valor inicial del rango es un valor grande, ya queislicetendría que iterar sobre el primer valor inicial-1 elementos antes de devolver elementos.

 7
Author: martineau,
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
2013-12-19 23:37:57

Desea utilizar el corte.

for item in listOfStuff[1:3]:
    print item
 3
Author: Håvard,
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
2011-03-31 15:21:37

Usando iter incorporado:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)
 1
Author: Elior Malul,
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
2018-06-26 16:58:42