[Python] Sort iterable by multiple conditions

Built-in functions: sorted

sorted(iterable[, key][, reverse])

--A function that returns a sorted list of the elements of the first argument ʻiterableas a return value. --The keyword argumentkeyis if the element of iterable is a tuple etc.key = lambda x: x[1] You can specify the number of elements to be used as a reference. (Default is None and compare as it is) --A bool value is given to the keyword argumentreverse`. True for descending order, False for ascending order (default is False [ascending order])

Reference site: 2. Built-in functions-Python3.5.1 documentation

Multi-condition sorting

Why did you want to sort by multiple conditions

After getting the file name list with glob etc. I want to sort files with file names (test_file_1.txt, test_file_2.txt,… test_file_19.txt, test_file_20.txt) by number. If you simply try to sort

sort_test_1.py


>>> import random
>>> file_names = ["test_file_{}.txt".format(num) for num in range(1, 21)]
>>> random.shuffle(file_names)
>>> sorted(file_names)
['test_file_1.txt', 'test_file_10.txt', 'test_file_11.txt', 
 'test_file_12.txt', 'test_file_13.txt', 'test_file_14.txt',
 'test_file_15.txt', 'test_file_16.txt', 'test_file_17.txt',
 'test_file_18.txt', 'test_file_19.txt', 'test_file_2.txt',
 'test_file_20.txt', 'test_file_3.txt', 'test_file_4.txt',
 'test_file_5.txt', 'test_file_6.txt', 'test_file_7.txt',
 'test_file_8.txt', 'test_file_9.txt']

Since we will start from the beginning, we want 1 to be followed by 2, but it will be 10. (In this case, changing the file name will solve the problem) Here, tuples are used to solve this problem.

Tuple comparison

The comparison of tuples in Python starts from the first element. If there are two e.g. (a, b, c) (d, e, f), compare a and b, b and e, and c and f in that order.

Therefore, if you set key as (x, y), x as a single digit number, and y as a file name, you can sort well.

This time, sort by putting the length of the file name in x.

sort_test_2.py


>>> file_names = ["test_file_{}.txt".format(num) for num in range(1, 21)]
>>> random.shuffle(file_names)
>>> sorted(file_names, key=lambda x: (len(x), x))
['test_file_1.txt', 'test_file_2.txt', 'test_file_3.txt',
 'test_file_4.txt', 'test_file_5.txt', 'test_file_6.txt',
 'test_file_7.txt', 'test_file_8.txt', 'test_file_9.txt',
 'test_file_10.txt', 'test_file_11.txt', 'test_file_12.txt',
 'test_file_13.txt', 'test_file_14.txt', 'test_file_15.txt',
 'test_file_16.txt', 'test_file_17.txt', 'test_file_18.txt',
 'test_file_19.txt', 'test_file_20.txt']

Summary

--Easy to use sorted in built-in functions --You can easily sort by multiple conditions by using tuples.

Recommended Posts

[Python] Sort iterable by multiple conditions
Sort by date in python
[Python] Sort
Python # sort
Sort by specifying conditions in CASTable
When specifying multiple keys in python sort
[Python] What is inherited by multiple inheritance?
Blender 2.9, Python, Select multiple meshes by coordinates
Sort by pandas
Sort the elements of the array by specifying the conditions
[Python] Sort the table by sort_values (pandas DataFrame)
[Python] How to sort instances by instance variables
Python> Sort by number and sort by alphabet> Use sorted ()
Sort tuple list in Python by specifying the ascending / descending order of multiple keys
Primality test by Python
Visualization memo by Python
Communication processing by Python
Bubble sort in Python
[Python] Create multiple directories
Python self-made class sort
[Memo] Python3 list sort
Python sort cheat sheet
Beamformer response by python
Custom sort in Python3
[Python] Sort collection types
[Python] Sort spreadsheet worksheets by sheet name with gspread
Python> Get a list of files in multiple directories> Use glob | Sort by modification time
[Python] Send gmail with python: Send one by one with multiple image files attached
Multiple regression expressions in Python
Speech recognition by Python MFCC
Sort by dict type value value
EXE Web API by Python
Newcomer training program by Python
Parameter setting by python configparser
Naturally sort Path in Python
Python basic dict sort order
Pin python managed by conda
Specify multiple list indexes (Python)
Sort huge files with python
Install multiple versions of Python
python in mongodb in descending sort
Keyword extraction by MeCab (python)
Separate numbers by 3 digits (python)
Markov switching model by Python
Python beginners organize bubble sort
[Rust / Python] Periodic boundary conditions
Python basics: conditions and iterations
Image processing by python (Pillow)
Decompress multiple compressed files (Python)
Python started by C programmers
Avoid multiple loops in Python
Sort by file modification date
Prohibit multiple launches in python
Platform (OS) determination by Python
About Python sort () and reverse ()
Sort the file names obtained by Python glob in numerical order
When you want to sort a multidimensional list by multiple lines
Sort of tuple array can be accelerated by specifying key (Python)