Custom Python List Sort

I was revising the old code and came across this:

alist.sort(cmp_items) def cmp_items(a, b): if a.foo > b.foo: return 1 elif a.foo == b.foo: return 0 else: return -1 

The code works (and I wrote it about 3 years ago!), But I can not find this thing anywhere in the Python document, and everyone uses sorted() to implement custom sorting. Can someone explain why this works?

+45
python sorting list
Aug 07 2018-12-12T00:
source share
3 answers

Described here.

The sort () method takes optional arguments to control the comparison.

cmp defines a user-defined comparison function of two arguments (a list of items) that must return a negative, zero, or positive number depending on whether the first argument is considered smaller, equal to or greater than the second argument: cmp = lambda x, y: cmp (x. lower (), y.lower ()). The default value is None.

+34
Aug 07 2018-12-12T00:
source share
β€” -

As a side note, there is a better alternative for implementing the same sorting:

 alist.sort(key=lambda x: x.foo) 

Or alternatively:

 import operator alist.sort(key=operator.attrgetter('foo')) 

See Sorting How To , it is very useful.

+57
Aug 07 2018-12-12T00:
source share

As in this example. You want to sort this list.

 [('c', 2), ('b', 2), ('a', 3)] 

exit:

 [('a', 3), ('b', 2), ('c', 2)] 

you must sort the two elements and the first

 def letter_cmp(a, b): if a[1] > b[1]: return -1 elif a[1] == b[1]: if a[0] > b[0]: return 1 else: return -1 else: return 1 

Finally:

just sort(letter_cmp)

+7
Mar 18 '16 at 3:26
source share



All Articles