[Tutor] Sorting list of tuples in two passes
Hugo Arts
hugo.yoshi at gmail.com
Sun Aug 28 19:23:09 CEST 2011
On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmi <contactdayo at gmail.com> wrote:
> Hi
>
> I have a list of tuples that each have four elements:
>
> [(firstName,lastName,userName,gidNumber),(.....)....]
>
> I'm trying to sort this list in two passes. First by gidNumber and then the
> subgroups by lastName. So far i've only been able to sort by gidNumber. But
> I can't seem to wrap my mind around lambda, which is what my browsing around
> seems to indicate is needed to achieve this?
>
> Thanks
>
> Dayo
>
Python's builtin sort is stable, which means that ordering of items
with the same key is preserved. This property means that you can do
multiple pass sorting very easily and efficiently just by sorting
twice:
>>> # we'll simplify the problem a bit and have tuples with just last name and id.
>>> l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)]
>>> l.sort(key=itemgetter(0))
>>> l
[('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)]
>>> l.sort(key=itemgetter(1))
>>> l
[('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)]
>>>
We sort by last name first, then sort again by id. As you can see, the
sorting of groups with the same id is preserved, and our list is now
in the correct order.
Hugo
More information about the Tutor
mailing list