¿Cómo seleccionar elementos secuenciales de una lista?

Roughly speaking I am looking for a more elegant alternative for this snippet:

# my_list = range(6) # example list
my_list = ["this", "is", "an", "example", "list"]
max = len(my_list)
for i, elem in enumerate(my_list, start=1):
     if i < max:
         print elem, my_list[i]

que produce:

this is
is an
an example
example list

Is there some builtin for that?

Edit: I should have said, that I took range(6) as a representant for any iterable to avoid confusion. The goal was to iterate over an iterable pairwise pictured by the result above.

preguntado el 10 de marzo de 12 a las 14:03

2 Respuestas

Yo suelo hacer esto:

# x = range(6)
x = ["this", "is", "an", "example", "list"]

for prv, nxt in zip(x, x[1:]):
    print prv, nxt

respondido 10 mar '12, 15:03

Sin embargo, esto no funcionará en python3 desde range es un generador. - strcat

Acabo de escribir range(6) as an example of an iterable. I should have chosen something more general. - Aufwind

@strcat: As far as I understand, range is just a placeholder for an example list. I won't really do this for range :). Let me edit to be more clear. - Avaris

Ah, I see. I thought you might want something that worked for generators too. - strcat

@strcat: Actually, range work like this in Python 3.2 (though not 3.1) -- range(6)[1:] == range(1,6) -- but I agree this is a special case. - DSM

There is no builtin, but the docs for the itertools module contains definition of the pairwise función que hace lo mismo.

respondido 10 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.