sort()是列表list的方法之一
L.sort(key=None, reverse=False)
sorted() 函数可以对任意可迭代对象排序。返回一个列表
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的list,而不是在原来的基础上进行的操作
# sorted()语法
sorted(iterable[, cmp[, key[, reverse]]])
参数说明:
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)]
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
原理:
print(sorted([True, False])) # [False, True]
# Boolean 的排序会将 False 排在前,True排在后
x.isdigit()的作用把iterable分成两部分,数字和非数字,数字在后,非数字在前
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit()]))
print(new_s1) # asdfGDSdsf234234578
x.isdigit() and int(x) % 2 == 0的作用是将数字部分分成两部分,偶数(在后)和奇数(在前)
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0]))
print(new_s1) # asdfGDSdsf335724248
x.isupper()的作用是在前面基础上,保证字母小写在前大写在后
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper()]))
print(new_s1) # asdfdsfGDS335724248
最后的x表示在前面基础上,对所有类别数字或字母排序
new_s1 = "".join(sorted(s, key=lambda x: [x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x]))
print(new_s1) # addffssDGS335722448
lst = [7, -8, 5, 4, 0, -2, -5]
要求:
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]
原文:https://www.cnblogs.com/pankypan/p/11074372.html