Python sort cheat sheet

The contents of Sort HOW TO — Python 3.5.1 Document and additional tips.

Sort function

list.sort()

--Sort the list and replace the original list. --There is no return value.

>>> a = [3, 0, 5, 1]
>>> a.sort()
>>> a
[0, 1, 3, 5]
>>> print(a.sort())  #There is no return value
None

sorted(list)

--Returns the result of sorting the list. --The original list is unchanged. --Can be used for other than lists.

>>> a = [3, 0, 5, 1]
>>> sorted(a)
[0, 1, 3, 5]
>>> a  #The original list remains unchanged
[3, 0, 5, 1]
>>> sorted(iter([3, 0, 5, 1]))  #Can be used for other than lists
[0, 1, 3, 5]

Reverse sort

--Specify reverse = True.

>>> a = [3, 0, 5, 1]
>>> sorted(a, reverse=True)
[5, 3, 1, 0]

Specify the sort key

--Specify a function or lambda expression in key.

>>> a = ["c", "aaa", "Bb"]
>>> sorted(a, key=lambda x: x.lower())
['aaa', 'Bb', 'c']
>>> sorted(a, key=str.lower)
['aaa', 'Bb', 'c']
>>> sorted(a, key=len)
['c', 'Bb', 'aaa']

Sorting lists with dictionaries, lists and tuples as elements

--By default, the elements are compared in order.

python


>>> a = [("b", 3), ("b", 1), ("a", 1), ("a", 2), ("c", 2)]
>>> sorted(a)
[('a', 1), ('a', 2), ('b', 1), ('b', 3), ('c', 2)]

--When specifying a key, using itemgetter is more concise than a lambda expression.

python


>>> a = [{"key1": 3}, {"key1": 1}]
>>> from operator import itemgetter
>>> sorted(a, key=itemgetter("key1"))
[{'key1': 1}, {'key1': 3}]

Sorting a list with classes as elements

--When specifying a key, using attr getter is more concise than a lambda expression.

python


>>> from datetime import date
>>> a = [date(2016, 1, 1), date(2015, 12, 1)]
>>> from operator import attrgetter
>>> sorted(a, key=attrgetter("month"))
[datetime.date(2016, 1, 1), datetime.date(2015, 12, 1)]

Composite sort

--Composite sorting is possible by further sorting the sort results. --Sort the keys with the lowest priority first.

python


>>> a = [("b", 3), ("b", 1), ("a", 1), ("a", 2), ("c", 2)]
>>> b = sorted(a, key=itemgetter(1), reverse=True)
>>> sorted(b, key=itemgetter(0))
[('a', 2), ('a', 1), ('b', 3), ('b', 1), ('c', 2)]

--Itemgetter and attrgetter can specify multiple keys at once, so use this if the descending and ascending order are the same for all keys.

python


>>> sorted(a, key=itemgetter(0, 1))
[('a', 1), ('a', 2), ('b', 1), ('b', 3), ('c', 2)]

Sort if it contains None

--If you sort normally, it will fail. --As a compound sort, specify Bool as None in the first key and the element itself in the second key.

>>> a = [3, 0, None, 5, 1]
>>> sorted(a)  #Sorting normally fails
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < int()
>>> sorted(a, key=lambda x: (x is None, x))  #None at the end
[0, 1, 3, 5, None]
>>> sorted(a, key=lambda x: (x is not None, x))  #None at the beginning
[None, 0, 1, 3, 5]

Python sort list with None at the end - Stack Overflow

Make classes sortable

--Implement __lt__ ().

class P(object):
    def __init__(self, gender, age):
        self.gender = gender
        self.age = age
    def __repr__(self):
        return "{:s}{:d}".format(self.gender, self.age)
    def __lt__(self, other):
        return (self.gender, self.age) < (other.gender, other.age)

a = [P("F", 30), P("F", 20), P("M", 20), P("M", 40), P("F", 10)]
print(sorted(a))

Merge multiple sorted iterables

-Use heapq.merge.

>>> import heapq
>>> list(heapq.merge([1, 3, 4, 7], [2, 5], [6]))
[1, 2, 3, 4, 5, 6, 7]

Sort huge text files

-Sort large text files in Python --Qiita

Recommended Posts

Python sort cheat sheet
PySpark Cheat Sheet [Python]
[Python3] Standard input [Cheat sheet]
[Python] Sort
Python # sort
Python Django Tutorial Cheat Sheet
Apache Beam Cheat Sheet [Python]
Python Computation Library Cheat Sheet ~ itertools ~
Curry cheat sheet
SQLite3 cheat sheet
pyenv cheat sheet
AtCoder cheat sheet in python (for myself)
Blender Python Mesh Data Access Cheat Sheet
Mathematical Optimization Modeler (PuLP) Cheat Sheet (Python)
conda command cheat sheet
PIL / Pillow cheat sheet
Linux command cheat sheet
Bubble sort in Python
Python self-made class sort
Spark API cheat sheet
[Memo] Python3 list sort
[Updating] Python Syntax cheat sheet for Java shop
Go language cheat sheet
Custom sort in Python3
[Python] Sort collection types
Python pdf cheat sheets
[Python] Sort spreadsheet worksheets by sheet name with gspread
tox configuration file cheat sheet
Sort Python module imports alphabetically
Naturally sort Path in Python
Python basic dict sort order
Sort huge files with python
Slack API attachments cheat sheet
python in mongodb in descending sort
Python beginners organize bubble sort
scikit learn algorithm cheat sheet
Sort by date in python
About Python sort () and reverse ()
Google Test / Mock personal cheat sheet
Continuation Passing Style (CPS) Cheat Sheet
[Python] Sort iterable by multiple conditions
Python
Sort large text files in Python
[Python] One-liner Stalin sort with 50 characters
sort
When specifying multiple keys in python sort
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
Curry cheat sheet [Description example list version]
[Reinventing the wheel] Human-powered tournament sort [Python]
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
A brief description of pandas (Cheat Sheet)
R code compatible sheet for Python users