Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@giwa

Custom sort in Python3

More than 5 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

0
Help us understand the problem. What is going on with this article?
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
giwa

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?