33 lines
811 B
Python
33 lines
811 B
Python
a= sorted([1,3,2,5,4])
|
|
print(a)
|
|
|
|
b= sorted([1,3,2,5,4],reverse=True)
|
|
print(b)
|
|
|
|
# 按绝对值排序
|
|
c= [-5, 2, -9, 1]
|
|
print(sorted(c,key=abs))
|
|
|
|
# 忽略大小写 按字母排序
|
|
d= ['apple','Banana','cherry']
|
|
print(sorted(d,key=lambda x:x.lower()))
|
|
print(sorted(d,key=str.lower))
|
|
|
|
# 按字典值排序
|
|
e= {'a':3,'b':2,'c':5,'d':4}
|
|
print(sorted(e.items(),key=lambda x:x[1],reverse=True))
|
|
|
|
# 按字符串长度排序
|
|
f= ['apple','Banana','cherry','date','a']
|
|
print(sorted(f,key=lambda x:len(x)))
|
|
|
|
# 多条件排序
|
|
# 先按成绩升序,再按姓名升序
|
|
# 如果成绩相同,按姓名升序
|
|
students = [
|
|
{"name": "Elice", "score": 85},
|
|
{"name": "Alice", "score": 85},
|
|
{"name": "Bob", "score": 92},
|
|
{"name": "Dave", "score": 78},
|
|
]
|
|
print(sorted(students,key=lambda x: (x["score"], x["name"]))) |