Python 根据列表中某字段排序:从基础到进阶 在 Python 开发中我们经常需要对列表List中的元素进行排序。如果列表中的元素是简单的数字或字符串可以直接使用sorted()或list.sort()方法。但如果列表中的元素是字典dict或自定义对象class并且需要根据某个字段key进行排序该怎么办呢本文将详细介绍Python 中如何根据列表中某字段排序涵盖字典列表排序、自定义对象排序以及高级排序技巧如多字段排序、降序排序等。1. 基础排序数字和字符串列表如果列表中的元素是数字或字符串可以直接使用sorted()或list.sort()numbers[3,1,4,1,5,9,2]sorted_numberssorted(numbers)# 升序print(sorted_numbers)# [1, 1, 2, 3, 4, 5, 9]numbers.sort(reverseTrue)# 降序原地修改print(numbers)# [9, 5, 4, 3, 2, 1, 1]字符串排序words[banana,apple,cherry,date]sorted_wordssorted(words)print(sorted_words)# [apple, banana, cherry, date]2. 字典列表排序根据某个键key排序如果列表中的元素是字典并且需要根据某个键如age、score排序可以使用sorted()的key参数。示例 1根据字典的某个键排序students[{name:Alice,age:20,score:90},{name:Bob,age:18,score:85},{name:Charlie,age:22,score:95}]# 按 age 升序排序sorted_by_agesorted(students,keylambdax:x[age])print(sorted_by_age) [ {name: Bob, age: 18, score: 85}, {name: Alice, age: 20, score: 90}, {name: Charlie, age: 22, score: 95} ] # 按 score 降序排序sorted_by_score_descsorted(students,keylambdax:x[score],reverseTrue)print(sorted_by_score_desc) [ {name: Charlie, age: 22, score: 95}, {name: Alice, age: 20, score: 90}, {name: Bob, age: 18, score: 85} ] 示例 2使用operator.itemgetter替代lambdaoperator.itemgetter可以替代lambda提高性能适用于大数据量fromoperatorimportitemgetter# 按 name 排序sorted_by_namesorted(students,keyitemgetter(name))print(sorted_by_name) [ {name: Alice, age: 20, score: 90}, {name: Bob, age: 18, score: 85}, {name: Charlie, age: 22, score: 95} ] 3. 自定义对象排序根据属性排序如果列表中的元素是自定义类的对象并且需要根据某个属性如age、score排序可以使用sorted()的key参数或实现__lt__方法。示例 1使用lambda按属性排序classStudent:def__init__(self,name,age,score):self.namename self.ageage self.scorescoredef__repr__(self):returnfStudent(name{self.name}, age{self.age}, score{self.score})students[Student(Alice,20,90),Student(Bob,18,85),Student(Charlie,22,95)]# 按 age 排序sorted_by_agesorted(students,keylambdax:x.age)print(sorted_by_age) [ Student(nameBob, age18, score85), Student(nameAlice, age20, score90), Student(nameCharlie, age22, score95) ] 示例 2实现__lt__方法推荐如果经常需要按某个属性排序可以在类中实现__lt__小于方法这样可以直接使用sorted()或list.sort()classStudent:def__init__(self,name,age,score):self.namename self.ageage self.scorescoredef__lt__(self,other):returnself.ageother.age# 按 age 升序排序def__repr__(self):returnfStudent(name{self.name}, age{self.age}, score{self.score})students[Student(Alice,20,90),Student(Bob,18,85),Student(Charlie,22,95)]# 直接排序无需 key 参数sorted_studentssorted(students)print(sorted_students) [ Student(nameBob, age18, score85), Student(nameAlice, age20, score90), Student(nameCharlie, age22, score95) ] 如果需要按不同属性排序可以动态修改__lt__或使用functools.cmp_to_key较复杂不推荐。4. 高级排序技巧(1) 多字段排序如果需要先按age排序再按score排序可以使用tuple作为keystudents[{name:Alice,age:20,score:90},{name:Bob,age:18,score:85},{name:Charlie,age:20,score:95},{name:David,age:18,score:80}]# 先按 age 升序再按 score 降序sorted_studentssorted(students,keylambdax:(x[age],-x[score])# 负号实现降序仅适用于数字)# 或者更通用的方式sorted_studentssorted(students,keylambdax:(x[age],x[score]),reverseFalse)# 先 age 升序再 score 升序# 如果需要 age 升序score 降序可以分两步排序students.sort(keylambdax:x[score],reverseTrue)# 先按 score 降序students.sort(keylambdax:x[age])# 再按 age 升序稳定排序print(sorted_students) [ {name: David, age: 18, score: 80}, {name: Bob, age: 18, score: 85}, {name: Alice, age: 20, score: 90}, {name: Charlie, age: 20, score: 95} ] (2) 降序排序使用reverseTrue实现降序numbers[3,1,4,1,5,9,2]sorted_descsorted(numbers,reverseTrue)print(sorted_desc)# [9, 5, 4, 3, 2, 1, 1](3) 自定义排序逻辑functools.cmp_to_key如果排序逻辑较复杂如按字符串长度排序可以使用functools.cmp_to_keyfromfunctoolsimportcmp_to_key words[banana,apple,cherry,date]# 自定义比较函数按字符串长度排序defcompare(a,b):iflen(a)len(b):return-1eliflen(a)len(b):return1else:return0sorted_wordssorted(words,keycmp_to_key(compare))print(sorted_words)# [date, apple, banana, cherry]5. 总结排序场景方法示例数字/字符串列表排序sorted()或list.sort()sorted([3, 1, 4])字典列表按某键排序sorted(list, keylambda x: x[key])sorted(students, keylambda x: x[age])自定义对象按属性排序sorted(list, keylambda x: x.attr)或__lt__sorted(students, keylambda x: x.age)多字段排序sorted(list, keylambda x: (x[key1], x[key2]))sorted(students, keylambda x: (x[age], x[score]))降序排序reverseTruesorted(numbers, reverseTrue)复杂排序逻辑functools.cmp_to_keysorted(words, keycmp_to_key(compare))推荐做法优先使用sorted()非原地排序或list.sort()原地排序。字典列表排序推荐lambda或operator.itemgetter。自定义对象排序推荐实现__lt__方法。多字段排序推荐使用tuple作为key。希望本文能帮助你掌握Python 中根据列表字段排序的各种方法