sorted(iterable[, key][, reverse])
--A function that returns a sorted list of the elements of the first argument ʻiterableas a return value. --The keyword argument
keyis 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 argument
reverse`. True for descending order, False for ascending order (default is False [ascending order])
Reference site: 2. Built-in functions-Python3.5.1 documentation
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.
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']
--Easy to use sorted in built-in functions --You can easily sort by multiple conditions by using tuples.
Recommended Posts