英文:
Alternating-direction tuple sort with key function in python
问题
我需要对一个包含两个元素的元组列表进行排序,但是我希望按照第二个值降序排序,然后按照第一个值升序排序。
例如:(0,1) < (1,1) < (1,0)
我认为可以通过比较函数来实现,但我想知道是否可以使用键函数来完成。
英文:
I need to sort a list of tuples (length 2) but specifically need it to sort by second value descending and then by first value ascending.
i.e. (0,1)<(1,1)<(1,0)
I think I could do it without too much trouble with a comparison function, but would like to know if it's doable with a key function.
答案1
得分: 1
你可以按照以下方式使用lambda键:
tlist = [
(1,1),
(0,1),
(1,0)
]
print(sorted(tlist, key=lambda x: (-x[1], x[0])))
输出结果:
[(0, 1), (1, 1), (1, 0)]
或者,不使用lambda...
def cf(t):
a, b = t
return -b, a
print(sorted(tlist, key=cf))
英文:
You could use a lambda key as follows:
tlist = [
(1,1),
(0,1),
(1,0)
]
print(sorted(tlist, key=lambda x: (-x[1], x[0])))
Output:
[(0, 1), (1, 1), (1, 0)]
Or, without lambda...
def cf(t):
a, b = t
return -b, a
print(sorted(tlist, key=cf))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论