How do I sort these?

Amaury afa.NOSPAM at neuf.fr
Fri Oct 28 17:57:09 EDT 2005


Sam Pointon a écrit :
>>unzip doesn't seem to work for me...
> 
> 
> It's not a part of the standard Python distribution, but this is a
> naive implementation (it doesn't react well to the list's contents
> having different lengths).
> 
> def unzip(seq):
>     result = [[] for i in range(len(seq[0]))]
>     for item in seq:
>         for index in range(len(item)):
>             result[index].append(item[index])
>     return result
> 
> 
>>>>unzip(zip(range(5), 'abcde'))
> 
> [[0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e']]
> 

unzip() could be also be written like this:

def unzip(seq):
     return zip(*seq)

Faster and nicer, isn't it?

Except that it returns a list of tuples:
 >>>unzip(zip(range(5), 'abcde'))
[(0, 1, 2, 3, 4), ('a', 'b', 'c', 'd', 'e')]

--
Amaury



More information about the Python-list mailing list