This link has been bookmarked by 109 people . It was first bookmarked on 31 Jul 2006, by Sprant Flere Imsaho Wu hanhadren Mrawhin Skell.
-
26 Jul 13
-
02 Jul 13
-
31 Mar 13
-
04 Nov 12
-
guaranteed to be stable.
-
That means that when multiple records have the same key, their original order is preserved.
-
key=itemgetter(0)
-
For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
-
key=attrgetter('grade')
-
-
21 Aug 12
-
Operator Module Functions
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.
-
-
26 May 12
-
13 May 12
-
11 Feb 12
-
18 Jan 12
-
14 Jan 12
-
29 Dec 11
-
22 Nov 11
-
08 Nov 11
-
30 Sep 11
-
27 Sep 11
-
16 Sep 11
-
25 Aug 11
-
15 Aug 11
-
09 May 11
-
19 Feb 11
-
23 Dec 10
-
10 Oct 10
-
06 Oct 10
-
02 Oct 10
-
04 Sep 10
-
26 Aug 10
-
10 Jun 10
-
06 Jun 10
-
30 Apr 10
-
19 Mar 10
-
you can sort tuples based on their second element using operator.itemgetter():
-
sorted(L, key=operator.itemgetter(1))
-
sorted(L, key=lambda x:(x[1], x[0]))
-
sorted(L, key=operator.itemgetter(1), reverse=True)
-
-
22 Oct 09
-
28 Sep 09
-
04 Aug 09
-
02 Jun 09
-
16 Apr 09
Alec Schueler"Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn't appear to be a single, central pl -
16 Mar 09
-
14 Mar 09
-
07 Mar 09
-
16 Feb 09
-
26 Nov 08
-
19 Oct 08
-
29 Sep 08
-
04 Sep 08
-
18 Aug 08
-
>>> a = [Spam(1, 4), Spam(9, 3), Spam(4, 6)] >>> a.sort(key=lambda obj: obj.eggs) >>> for spam in a: >>> print spam.eggs, str(spam) 3 12 4 5 6 10
-
-
23 Jun 08
-
17 Apr 08
-
17 Jan 08
-
09 Jan 08
-
24 Dec 07
-
04 Dec 07
Alberto FernandezPython lists have a built-in sort() method. There are many ways to use it to sort a list and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here.
algorithms code development documentation programming python reference sorting
-
27 Nov 07
-
21 Mar 07
-
17 Mar 07
-
16 Mar 07
-
23 Feb 07
-
12 Feb 07
-
12 Nov 06
-
31 Jul 06
-
21 Mar 06
-
10 Feb 06
-
06 Jan 06
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.