[Tutor] Sorting 2-d data

Kent Johnson kent37 at tds.net
Sun Sep 13 16:12:02 CEST 2009


On Sun, Sep 13, 2009 at 1:17 AM, Lie Ryan <lie.1296 at gmail.com> wrote:
> if you have data like this:
> mylist = [
>    [3, 4, 3, 2, 1],
>    [2, 1, 1, 1, 1],
>    [4, 2, 2, 1, 2],
>    [1, 3, 1, 1, 1],
> ]
>
> you can use mylist.sort(key=lambda x: x[0])

You can omit the key parameter completely in this case, unless you
want to preserve the order of lines whose first element are the same.
The default comparison of lists is lexicographic, meaning it will
compare the first element, if they are the same then compare the
second, etc.

> if your data is like this:
> mylist = [
>    [3, 2, 4, 1],
>    [4, 1, 2, 3],
>    [3, 1, 2, 1],
>    [2, 1, 1, 1],
>    [1, 1, 2, 1],
> ]
>
> you can use zip(*mylist) to transform your data to row-first list, sort
> using the above method, then zip(*mylist) again. Beware that zip(*mylist)
> returns a list of tuples even if the original data is list of lists. I think
> there should be an easier (and faster) way, that others can point out.

zip() is the best method I know to do this.

Kent


More information about the Tutor mailing list