1. Sort sort, sorted,,,,,reverse
list = [5, 23, 45, 23, 34, 1, 77, 89, 56, 34, 5, 3]
list.sort()
print(list)
print(sorted(list, reverse=True))
list.reverse()
print(list)
Both sort and sorted accept the parameter reverse=True or False, indicating the ascending and descending order of sorting
2. Sort a certain part specified by the element, and sort by keywords
s = ['Chr1-10.txt','Chr1-1.txt','Chr1-2.txt','Chr1-14.txt','Chr1-3.txt','Chr1-20.txt','Chr1-5.txt']
I want to sort by the size of the numbers after - in ascending order . to use the key
sorted(s, key=lambda d : int(d.split('-')[-1].split('.')[0]))
['Chr1-1.txt', 'Chr1-2.txt', 'Chr1-3.txt', 'Chr1-5.txt', 'Chr1-10.txt', 'Chr1-14.txt', 'Chr1-20.txt']
This is the function of the key. The keyword for sorting is usually a lambda function. Of course, you can also define this function in advance. If you don't talk about this keyword and convert it to an integer, the result is this:
sorted(s, key=lambda d : d.split('-')[-1].split('.')[0])
['Chr1-1.txt', 'Chr1-10.txt', 'Chr1-14.txt', 'Chr1-2.txt', 'Chr1-20.txt', 'Chr1-3.txt', 'Chr1-5.txt']
This is equivalent to treating this keyword as a string. Obviously, in python, '2' > '10'
You can customize the key you want, such as key = lambda x : len(x) to sort by the length of the sequence. key= lambda x : (x[1], x[0]) by two elements, then the first and so on. . .