34

If i have a list of numbers [4,2,5,1,3] I want to sort it first by some function f and then for numbers with the same value of f i want it to be sorted by the magnitude of the number.

This code does not seem to be working.

list5 = sorted(list5)
list5 = sorted(list5, key = lambda vertex: degree(vertex)) 

Secondary sorting first: list5 is sorted based on magnitude. Primary sorting next: list5 is sorted based on some function of the numbers.

4

4 回答 4

84

按 (firstkey, secondkey) 元组对其进行排序:

sorted(list5, key=lambda vertex: (degree(vertex), vertex))
于 2013-04-24T13:44:18.320 回答
5

来自关于排序的 Python 3 文档

from operator import itemgetter, attrgetter
student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

#The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:

sorted(student_tuples, key=itemgetter(1,2))
sorted(student_objects, key=attrgetter('grade', 'age'))
于 2016-04-12T04:04:47.073 回答
4

在电话上,但您可以按元组排序。

sorted(list5, lambda x: (degree(x),x))

如果需要,请不要忘记反向标志。

于 2013-04-24T13:49:45.070 回答
0

这就是我会做的。

s = ['a', 'ac', 'b', 'ab']
s.sort(key=lambda x: (x[0], x[1]) if len(x)>1 else (x[0],))

结果:

['a', 'ab', 'ac', 'b']
于 2022-02-24T22:33:25.550 回答