[Tutor] when do I use this?
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Tue Mar 16 07:59:36 EST 2004
Em Mon, 15 Mar 2004 15:39:33 -0900, Tim Johnson <tim at johnsons-web.com>
atirou este peixe aos pinguins:
>* Christopher Spears <cspears2002 at yahoo.com> [040315 15:22]:
>> Several times I have iterated over a sequence with
>> some code that looks like this:
>
> I'm going to put in my two cents worth because
> I've thus far taken a very simplistic approach
> to iteration myself:
>
>> for f in range(len(files)):
>
> Suppose one had several sequences that were of the
> same length. Then with the approach above, one
> could use <f> to access each of them.
>
> However, I believe that there are more 'elegant'
> and 'pythonesque' ways of iterating over multiple
> sequences, so I'm looking forward to more comments.
>
Use zip.
>>> help(zip)
Help on built-in function zip:
zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th
element
from each of the argument sequences. The returned list is
truncated
in length to the length of the shortest argument sequence.
>>>
For example, the following should give you a clue (it also uses tuple
unpacking):
>>> lst = ["some", "list", "of", "words"]
>>> print zip(range(len(lst)), lst)
[(0, 'some'), (1, 'list'), (2, 'of'), (3, 'words')]
>>> for index, word in zip(range(len(lst)), lst):
... print "lst[%d]=%s" % (index, word)
...
lst[0]=some
lst[1]=list
lst[2]=of
lst[3]=words
With my best regards,
G. Rodrigues
More information about the Tutor
mailing list