Help us understand the problem. What is going on with this article?

Custom sort in Python3

More than 3 years have passed since last update.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした