Python sorted sorting method summary, pythonsorted
This article describes how to sort by sorted in Python. We will share this with you for your reference. The details are as follows:
# Example 1. sort seq = [2, 4, 3, 1, 2, 3] by the number of times the element appears # sort by the number of times seq2 = sorted (seq, key = lambda x: seq. count (x) print (seq2) # [4, 1, 3, 3, 2, 2, 2] # improvement: First, priority, by number of times, the second priority is seq3 = sorted (seq, key = lambda x :( seq. count (x), x) print (seq3) # [1, 4, 3, 3, 2, 2, 2] ''' principle: first, compare the first value of the tuples. (Note: False <True) if the values are equal, the next value of the tuples is compared, and so on. '''
Running result:
# Example 2. this is a string sorting rule: lower case <upper case <odd number <even number s = 'asdf234gdsf23 's2 = "". join (sorted (s, key = lambda x: (x. isdigit (), x. isdigit () and int (x) % 2 = 0, x. isupper (), x) print (s2) # addffssDGS33224
Running result:
# Example 3. one interview question: list1 = [7,-8, 5, 4, 0,-2,-5] # requirement 1. A positive number is in the first negative number in the last 2. positive numbers from small to large 3. negative number from large to small list2 = sorted (list1, key = lambda x :( x <0, abs (x) print (list2) # [,-2, -5,-8]
Running result: