在Python中使用键函数进行交替方向元组排序

huangapple go评论91阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2023年8月8日 23:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定