Reverse zip() ?

Zac Burns zac256 at gmail.com
Tue Dec 2 19:47:27 EST 2008


There is a problem with this however, which prompted me to actually
write an unzip function.

One might expect to be able to do something like so (pseudocode)...

def filesAndAttributes():
   files = walk()
   attributes = [attr(f) for f in files]
   return zip(files, attributes)

files, attributes = zip(*filesAndAttributes())

The corner case is when dealing with empty lists and there aren't
enough items to unpack.

The unzip function therefore has an elementsForEmpty keyword that
handles this case. Perhaps something like this could be added to zip?
I have not (yet) dealt with the PEP process, so I'm not sure where
that starts. Perhaps a discussion could start here.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games



On Tue, Dec 2, 2008 at 4:14 PM, John Machin <sjmachin at lexicon.net> wrote:
> On Dec 3, 7:12 am, Stefan Behnel <stefan... at behnel.de> wrote:
>> Andreas Waldenburger wrote:
>> > we all know about the zip builtin that combines several iterables into
>> > a list of tuples.
>>
>> > I often find myself doing the reverse, splitting a list of tuples into
>> > several lists, each corresponding to a certain element of each tuple
>> > (e.g. matplotlib/pyplot needs those, rather than lists of points).
>>
>> > This is of course trivial to do via iteration or listcomps, BUT, I was
>> > wondering if there is a function I don't know about that does this
>> > nicely?
>>
>> I think you're asking about zip():
>>
>>         >>> l=[1,2,3]
>>         >>> zip(l,l)
>>         [(1, 1), (2, 2), (3, 3)]
>>         >>> zip(*zip(l,l))
>>         [(1, 2, 3), (1, 2, 3)]
>>
>
> Here's a version that makes it slightly easier to comprehend:
>
> Q: I know how to zip sequences together:
> | >>> a = (1, 2, 3)
> | >>> b = (4, 5, 6)
> | >>> z = zip(a, b)
> | >>> z
> | [(1, 4), (2, 5), (3, 6)]
> but how do I reverse the process?
>
> A: Use zip()!
> | >>> a2, b2 = zip(*z)
> | >>> a2
> | (1, 2, 3)
> | >>> b2
> | (4, 5, 6)
>
> Cheers,
> John
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list