How to sort this kind of list easily?
Anthony Baxter
anthonybaxter at gmail.com
Fri Aug 20 06:38:05 EDT 2004
On Fri, 20 Aug 2004 17:03:51 +0800, BruceKL WhoH <brucewhohkl at gawab.com> wrote:
> Hi,all
> I have a list like [(id,string),...],for example:
>
> [(1,'xxxxx'),(7,'ppppp'),(4,'gggggg'),...]
>
> I want to sort this list according to the id of each element. After sorting,the list will become:
>
> [(1,'xxxxx'),(4,'gggggg'),(7,'ppppp')...]
>>> l=[(1,'xxxxx'),(7,'ppppp'),(4,'gggggg'),(2,'ffff'),(12,'hhhhh')]
>>> l.sort()
>>> print l
[(1, 'xxxxx'), (2, 'ffff'), (4, 'gggggg'), (7, 'ppppp'), (12, 'hhhhh')]
list.sort sorts tuples by first argument, then second &c. If you want a
custom sort order, look at the decorate-sort-undecorate pattern.
Anthony
More information about the Python-list
mailing list