sorting many arrays from one...

Alex Martelli aleax at aleax.it
Tue Jul 9 10:17:30 EDT 2002


Shagshag13 wrote:

> 
> "Duncan Booth" <duncan at NOSPAMrcp.co.uk> a écrit dans le message de news:
> Xns924692F5BE4Cduncanrcpcouk at 127.0.0.1...
> 
>>   drive, other1, other2, other3 = map(list, zip(*aux_list))
> 
> fine ! and with map ! but i still have another question i didn't
> understand how this works (i think i didn't get zip(*aux_list))

Using *whatever as an actual argument to any function f passes the
items of whatever, one after the other, as the actual arguments
of f.  So, zip(*aux_list) is just like
    zip(aux_list[0], aux_list[1], aux_list[2])
and so on for however many items aux_list has.  All clear so far?

Now, what zip does is: for each argument take the first item and
zip them into one tuple; then for each argument take the second item and
zip them into a second tuple; and so on until the shortest argument
is exhausted -- then, done, return the list of all the tuples.

So, here zip(*aux_list) returns a list where: the first item is
a tuple made up of -- first item of aux_list[0], then, first item
of aux_list[1], then, first item of aux_list[2], and so on.  But
the way we built aux_list, those "first items" are exactly the
items of the 'drive' list.  So, the first item of zip's return
list is (a tuple form of) the sorted 'drive'.  Similarly, the
second item is a tuple form of 'other1' permuted according to
the sort on drive, etc, for a total of four tuples in our case.

All that map has left to do is turn each tuple into a list again.


Basically this is what I meant by mentioning that (in a sense --
specifically, only for sequences all of the same length, and net
of list vs tuple considerations) zip is its own inverse.

zip(*zip(wha,te,ver)) == [wha, te, ver] if the sequences wha,
te, and ver, are all tuples of the same length...


Alex




More information about the Python-list mailing list