Custom sort in Python3

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

Recommended Posts

Custom sort in Python3
[Python] Sort
python in mongodb in descending sort
Python # sort
Sort by date in python
Sort large text files in Python
Custom state space model in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
When specifying multiple keys in python sort
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python