making zip with list comprehensions

Bengt Richter bokr at oz.net
Sat Jul 13 02:06:19 EDT 2002


On Tue, 09 Jul 2002 11:06:54 +0100, Jonathan Hogg <jonathan at onegoodidea.com> wrote:

>On 9/7/2002 10:56, in article oryW8.234$xm1.54155 at news0.telusplanet.net,
>"Ian McMeans" <imcmeans at home.com> wrote:
>
>> I was idly trying to replicate zip's (the function) behavior using list
>> comprehensions, but I couldn't do it.
>> 
>> Can anyone? I came up with these, but they're ugly.
>> 
>>>>> [(x,y) for x in ['a','b','c'] for y in ['d','e','f'] if
>> ['a','b','c'].index(x) == ['d','e','f'].index(y)]
>> [('a', 'd'), ('b', 'e'), ('c', 'f')]
>> 
>> This is ugly because it loops far too many times =)
>> 
>>>>> [ (['a','b','c'][x], ['d','e','f'][x]) for x in range(3)]
>> [('a', 'd'), ('b', 'e'), ('c', 'f')]
>> 
>> This isn't so bad. Does anyone have better suggestions?
>> 
>> 
>
>Best I could come up with is:
>
>>>> xs = [ 'a', 'b', 'c' ]
>>>> ys = [ 'd', 'e', 'f' ]
>>>> 
>>>> [ ( x, yi.next() ) for yi in (iter(ys),) for x in xs ]
>[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>>> 
>
>I think the lack of a clean way of doing lockstep iteration is exactly why
>'zip' was invented ;-)
>

Well,
 >>> [(x,y) for x,y in map(None, xs, ys)]
 [('a', 'd'), ('b', 'e'), ('c', 'f')]

is generated as a list comprehension, though it's kind of silly, considering

 >>> map(None, xs, ys)
 [('a', 'd'), ('b', 'e'), ('c', 'f')]

;-)

Regards,
Bengt Richter



More information about the Python-list mailing list