Python BIF built-in function -- sorting sort, sorted (2)

1. Sort sort, sorted,,,,,reverse

    1. Simple sorting
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)

The list.sort() function is to sort the list itself, and there is no return value, so the return is None. The same is true for reverse
Solution:
    1)
        list.sort()
        return list

    2)
        return sorted(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. . .

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326778429&siteId=291194637