LoginSignup
1
0

More than 5 years have passed since last update.

Custom sort in Python3

Posted at

In Python2, sort has input cmp to define custom comparizon. However, python3 removed it.

In Pyhton2

>>> def compare(a, b):
...     """Comparison that ignores the first letter"""
...     return cmp(a[1:], b[1:])
>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(cmp=compare)
>>> names
['Adam', 'John', 'Donald']

In Python3, we can just use key.

>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(key=lambda x: x[1:])
>>> names
['Adam', 'John', 'Donald']

complex sort:
Sort word count. Data is represented by tuple: (word, count).
1. sort by count in descending order
2. if count is same, sort them with alphebet order of word

>>> l = [('betty', 1), ('a', 1), ('butter', 2)]
>>> def custom_key(x):
...     return -x[1], x[0]
...
>>> l.sort(key=custom_key)
>>> l
[('butter', 2), ('a', 1), ('betty', 1)]

How this works?
In comparison, python check first element of tuple. If they are same, compare the next element in tuple. Therefore, sort by count in descending order means first tuple and if count is same means second tuple of element.

ref:
http://python3porting.com/preparing.html

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0