Python sort () and sorted ()
sort and sorted differences:
sort()
sort () method is one of a list of list
L.sort(key=None, reverse=False)
sorted()
sorted () function can be any sort objects iteration. Returns a list
The method is applied on the sort of the list, sorted can be sorted objects operate all iterations.
sort method returns a list of the operation of the existing list operation, no return value, and built-in functions sorted method returns a new list, rather than on the basis of the original
# sorted()语法
sorted(iterable[, cmp[, key[, reverse]]])
Parameter Description:
- iterable - iterables
- cmp - compare function, the two parameters, parameter values are taken from the subject may be iterative, this function must comply with the rules is greater than 1 is returned, it is less than -1, 0 is returned equals
- key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to sort
- reverse - collation, reverse = True descending, reverse = False ascending (default)
Sort of a single rule:
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
new_students = sorted(students, key=lambda s: s[2])
print(new_students) # [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Multiple sort rule:
s = 'asdf234GDSdsf234578' # 排序:小写-大写-奇数-偶数
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x]))
print(new_s1) # addffssDGS335722448
principle:
print(sorted([True, False])) # [False, True]
# Boolean 的排序会将 False 排在前,True排在后
Action x.isdigit () of the iterable into two parts, digital and non-digital, digital after, the front non-digital
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit()])) print(new_s1) # asdfGDSdsf234234578
x.isdigit () and int (x) effect% 2 == 0 is the digital portion into two parts, an even number (in the rear) and odd (first)
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0])) print(new_s1) # asdfGDSdsf335724248
Action x.isupper () is the basis of the foregoing, to ensure that the front uppercase letter lowercase after
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper()])) print(new_s1) # asdfdsfGDS335724248
X represents the last in front, based on the sort of numbers or letters all categories
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x])) print(new_s1) # addffssDGS335722448
A face questions
lst = [7, -8, 5, 4, 0, -2, -5]
Claim:
- After positive negative in the front
- A positive number from small to large
- Negative descending
lst = [7, -8, 5, 4, 0, -2, -5]
new_lst1 = sorted(lst, key=lambda x: [x < 0, x < 0 and -x, x >= 0 and x]) # -3 < 0 and -(-3) ==> 3
new_lst2 = sorted(lst, key=lambda x: [x < 0, abs(x)])
print(new_lst1) # [0, 4, 5, 7, -2, -5, -8]
print(new_lst2) # [0, 4, 5, 7, -2, -5, -8]