any such thing as list interleaving?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Sat Jul 12 18:12:24 EDT 2003


On Sat, 12 Jul 2003 14:00:49 -0700, Tom Plunket <tomas at fancy.org>
wrote:

>
>I find myself often doing the following sort of thing (sorry for
>lack of whitespace, I don't want the line to break):
>
>for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)):
>   # ...
>
>This definitely seems like a roundabout way to loop through
>parallel lists together.  Is this map routine truly the easiest/
>best/most straight-forward way to do a for loop through parallel
>lists, if I feel that the Python anti-idom of:
>

Check the zip builtin:

>>> 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 index in range(len(myList)):
>   entry = aList(index)
>   anotherEntry = anotherList(index)
>   # ...
>
>???
>
>This also brings up a similar problem for me when iterating over
>dictionaries:
>
>for key in myDict:
>   value = myDict[key]
>   # ...
>

Fire the interpreter and type:

>>> help(dict)

As it's a long stretch of text, I'll just post the relevant part:

 |  iteritems(...)
 |      D.iteritems() -> an iterator over the (key, value) items of D
 |  

>This seems a pretty sloppy way to go about it, imo.  There must
>be something more in the Python spirit!  :)
>
>Thanks.
>
>-tom!

With my best regards,
G. Rodrigues




More information about the Python-list mailing list