[Tutor] Sorting 2-d data
Rich Lovely
roadierich at googlemail.com
Sun Sep 13 14:27:41 CEST 2009
2009/9/13 Lie Ryan <lie.1296 at gmail.com>:
> Wayne wrote:
>>
>> Hi,
>>
>> I have a set of data that looks something like this:
>>
>> 3, 4, 3, 2, 1
>> 2, 1, 1, 1, 1
>> 4, 2, 2, 1, 2
>> 1, 3, 1, 1, 1
>>
>> I want to be able to sort it by the first column, keeping the rest of the
>> values in the same position relative to the original:
>>
>> 1, 3, 1, 1, 1
>> 2, 1, 1, 1, 1
>> 3, 4, 3, 2, 1
>> 4, 2, 2, 1, 2
>>
>> and I'm wondering if there are any included ways to sort data like this.
>> I've currently got a 2d list by columns, but I could easily convert that to
>> rows if it would work better.
>>
>
> 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])
>
> sorted(mylist, key=lambda x: x[0]) works as well if you need a new list
>
> 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.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
This is another way, but will probably be slower than re-zipping into
row-major order.
keys = mylist[0]
myNewList = []
for L in mylist:
decoratedList = zip(keys, L)
decoratedList.sort(key=lambda x: x[0])
undecoratedList = map(lambda x: x[1], decoratedList)
myNewList.append(undecoratedList)
This is known as the decorate-sort-undecorate pattern.
It is possible to turn it into a one line comprehension:
myNewList = [[decorated[1] for decorated in sorted(zip(mylist[0], L),
key=lambda t: t[0])] for L in mylist]
I'm not suggesting you do it like this, but it's always useful to
learn new patterns.
--
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor
mailing list