Sorting functions are often used in programs. Python provides sort and sorted functions, one for sorting in place and the other for returning the new result after sorting
1. Parameters
##Function prototype:
sort([cmp[, key[, reverse]]])
means that the sort method accepts three parameters, all of which can be omitted. The default is ascending order.
The first parameter cmp is a comparison function. How to compare two parameters (elements of a list)? For comparison of built-in types such as integers, the method is very intuitive. , but for comparisons of custom types, you have to define the comparison function yourself. The function returns 0, which means the two numbers are equal, and returns a negative number, which means the first parameter is smaller, and the first parameter is ranked behind the second parameter. .
#The second parameter key is the attribute of the comparison list element.
The third parameter reverse is of type bool, which means whether to reverse (sort in reverse order)
①, cmp parameter example:
#cmp 函数,两个数倒过来比较 注!只能在python2.0上运行 s = [1, 2, 3, 4, 5] s.sort(cmp=lambda a, b:cmp(b, a)) print s # [5, 4, 3, 2, 1]
②, Common parameter key, reverse usage method , Code:
# key 指定排序方式 reverse 是否反排序 li = ['x11','abc323','e26','112ddd','fstgd2'] li.sort(key=len,reverse=True) # 用长度进行排序,从大到小进行排序 print(li) # ['abc323', '112ddd', 'fstgd2', 'x11', 'e26'] li.sort(key=lambda x:x[-1]) # key可以指定lambada函数x为列表中每个元素 print(li) # 元素的最后一个字符进行排序 # ['x11', 'fstgd2', 'abc323', 'e26', '112ddd'] li = zip(range(10),range(10)[::-1]) # 列表中元素为元祖是排序 print(li,type(li)) # <zip object at 0x000000E7F75504C8> <class 'zip'> li = list(li) print(li) # [(0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)] li.sort(key=lambda x:x[-1]) print(li) # [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] #**注!默认sort也是会对列表中元祖进行排序的 li.sort() print(li) # (0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)]
The parameter key can be: key=int, key=len, key=lambda...
2. Sorting
①. How to output the keys in the dict from small to large according to value- value?
dic = {'z':1, 'y':4,'x':2,'g':3,'sg':3} dic= sorted(dic.items(),key=lambda x:x[1]) print(dic) # [('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)]
Convert to dictionary after sorting:
from collections import OrderedDict dic = {'z':1, 'y':4,'x':2,'g':3,'sg':3} dic= OrderedDict(sorted(dic.items(),key=lambda x:x[1])) print dic # OrderedDict([('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)]) for k,v in dic.items(): print k,v # z 1 # x 2 # sg 3 # g 3 # y 4
②,Given a string containing only uppercase and lowercase letters and numbers, sort it to ensure:
All lowercase letters come before uppercase letters
All letters come before numbers
All odd numbers come before even numbers
s = "Sorting1234" def sort_str(x): # x 传入的每个元素 if x.isdigit(): if int(x) % 2 == 0: return (4,x) # 返回的是元祖,元祖可进行排序 return (3,x) elif x.islower(): return (0,x) elif x.isupper(): return (1,x) li = sorted(s,key=sort_str) print(li) # ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4'] string = ''.join(li) print(string) # ginortS1324
More concise code:
s = "Sorting1234" s ="".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x))) print(s) # ginortS1324
The above is the detailed content of A brief discussion on sorting in Python. For more information, please follow other related articles on the PHP Chinese website!