looping through a list of lists.

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Wed Oct 8 13:31:13 EDT 2003


Peter Otten wrote:

> Rob Hunter wrote:
> 
> 
>>The responder to this post has a cool way of doing it, but it won't
>>work (I believe) if you have an arbitrary number of sublists.  Can you
>>clarify the problem?  Do you have an arbitrary number of sublists?  Or
>>is it always 3?
> 
> 
> I you are referring to the zip trick posted by SBrunning at trisystems.co.uk,
> it *does work for an arbitrary number of sublists, but not for
> arbitrary-length sublists:
> 
> 
>>>>for loc in zip(*"alpha beta gamma delta".split()):
> 
> ...     print loc
> ...
> ('a', 'b', 'g', 'd')
> ('l', 'e', 'a', 'e')
> ('p', 't', 'm', 'l')
> ('h', 'a', 'm', 't')
> 
> 
> Peter

Consider the following:

PythonWin 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - 
see 'Help/About PythonWin' for further copyright information.
 >>> l = [range(0, 5), range(1, 7), range(3, 5)]
 >>> l
[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [3, 4]]
 >>> for e in zip(*l):
... 	print e
... 	
(0, 1, 3)
(1, 2, 4)
 >>> for e in map(None, *l): print e
...
(0, 1, 3)
(1, 2, 4)
(2, 3, None)
(3, 4, None)
(4, 5, None)
(None, 6, None)
 >>>

It pads missing elements with Nones. Is it what you need?

zip(*l) is similar to zip(l[0], l[1], ...., l[len(l) - 1])---it 
substitutes list elements to function parameters.

HTH,
anton.





More information about the Python-list mailing list