标题
#升序排序,降序只需添加括号内 reverse=True
list = [10,5,20,15,25]
#1.sort() 排序
list.sort()
print("list",list)
# 2.sorted() 降序排序 sorted
list1 = [10,5,20,15,25]
list1_1=sorted(list1,reverse=True)
print("list1_1",list1_1)
list2 = [("AAAA",10),("CCCC",5),("JJJJ",20),("BBBB",15),("FFFF",25)]
list2_1=sorted(list2,key=itemgetter(1),reverse=True) #按照第二个属性 排序
print("list2_1",list2_1)
结果:
list: [5, 10, 15, 20, 25]
list1_1: [25, 20, 15, 10, 5]
list2_1: [('FFFF', 25), ('JJJJ', 20), ('BBBB', 15), ('AAAA', 10), ('CCCC', 5)]
二维 List 排序
list = [["A",23],["A",34],["C",13],["B",12],["C",12]]
list.sort(key=itemgetter(1), reverse=True) #按照二维list的第二位参数降序排序
list.sort(key=itemgetter(0)) #按照二维list的第一位参数升序排序
print(list)
结果:[['A', 34], ['A', 23], ['B', 12], ['C', 13], ['C', 12]]
二维 List 嵌套 字典 重排序
list = [[{"name":"Jason","age":43},{"name":"Tony","age":34}],[{"Oprah":"2012-1-2","age":20},{"name":"Reach","age":32}],[{"Ray":"2012-1-2","age":39},{"name":"Elaine","age":29}]]
list1 = []
#对二维list中的 字典 进行排序
for i in range(len(list)):
sorted_lt = sorted(list[i], key=operator.itemgetter('age'),reverse=True)
list1.append(sorted_lt)
#再对 二维 list 排序
for m in range(len(list1)-1):
for n in range(m+1,len(list1)):
if list1[m][0]["age"] < list1[n][0]["age"] :
temp = list1[n];
list1[n] = list1[m];
list1[m] = temp;
print(list1)
结果:[[{'name': 'Jason', 'age': 43}, {'name': 'Tony', 'age': 34}],
[{'Ray': '2012-1-2', 'age': 39}, {'name': 'Elaine', 'age': 29}],
[{'name': 'Reach', 'age': 32}, {'Oprah': '2012-1-2', 'age': 20}]]