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.
如果我有一个数字列表[4,2,5,1,3]我想先用某个函数f对它进行排序,然后对于f值相同的数字,我想用数字的大小对它排序。
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.
次要排序首先:清单5是根据大小排序的。接下来是主排序:清单5是根据数字的某个函数排序的。
3 个解决方案
#1
35
Sort it by a (firstkey, secondkey) tuple:
按(firstkey, secondkey)元组排序:
sorted(list5, key=lambda vertex: (degree(vertex), vertex))
#2
2
From the Python 3 docs on sorting
来自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'))
#3
2
On a phone, but youcan sort by tuple.
在电话上,你可以按元组排序。
sorted(list5, lambda x: (degree(x),x))
Don't forget the reverse flag if you need it.
如果需要,不要忘记反向标志。
#1
35
Sort it by a (firstkey, secondkey) tuple:
按(firstkey, secondkey)元组排序:
sorted(list5, key=lambda vertex: (degree(vertex), vertex))
#2
2
From the Python 3 docs on sorting
来自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'))
#3
2
On a phone, but youcan sort by tuple.
在电话上,你可以按元组排序。
sorted(list5, lambda x: (degree(x),x))
Don't forget the reverse flag if you need it.
如果需要,不要忘记反向标志。