简体   繁体   English

Python lambda函数对元组列表进行排序

[英]Python lambda function to sort list of tuples

Initially, a list of tuples is sorted by their second value and their third value.最初,元组列表按其第二个值和第三个值排序。

tlist = [('a', 1, 14), ('a', 1, 16), ('b', 1, 22), 
        ('a', 2, 1), ('c', 2, 9), ('d', 2, 11), ('d', 2, 12)]

Trying to sort this list of tuples by their second value, reverse by their third value ;尝试按第二个值对这个元组列表进行排序,按第三个值反转 that is, want the output of the list to be sorted like so:也就是说,希望list的输出像这样排序:

tlist= [('b', 1, 22), ('a', 1, 16), ('a', 1, 14), 
        ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]

This is what I have tried so far as seen in this answer :到目前为止,这是我在这个答案中看到的尝试:

tlist = sorted(tlist, key=lambda t: return (t[0], t[1], -t[2]))

but it does not work;但它不起作用; gives a return outside of function error.给出return outside of function错误return outside of function

Any ides of how to get the desired output?关于如何获得所需输出的任何想法?

EDIT编辑

This question provides very good resources and perhaps all someone would need to go ahead and tackle my specific question.这个问题提供了非常好的资源,也许所有人都需要继续解决我的具体问题。 However, given my low level of experience and my specific instance of sorting with different sorting criteria (as described on the description above), I think this is no duplicate.但是,鉴于我的经验水平较低,并且我使用不同的排序标准进行排序的具体实例(如上面的描述所述),我认为这不是重复的。

A lambda expression does not use a return statement.lambda 表达式不使用return语句。 You should thus drop the return keyword.因此,您应该删除return关键字。

You also seem to sort first on the first element of the tuples.您似乎也首先对元组的第一个元素进行排序。 In order to only take the second element and use descending order of the third element as a tie breaker, you should rewrite the lambda to:为了只取第二个元素并使用第三个元素的降序作为决胜局,您应该将 lambda 重写为:

lambda t: (t[1],-t[2])

Or putting it all together:或者把它们放在一起:

tlist = sorted(tlist, key=lambda t: (t[1],-t[2]))

Running this in python3 generates:python3运行它会生成:

>>> tlist= [('b', 1, 22), ('a', 1, 16), ('a', 1, 14), 
...         ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]
>>> tlist = sorted(tlist, key=lambda t: (t[1],-t[2]))
>>> list(tlist)
[('b', 1, 22), ('a', 1, 16), ('a', 1, 14), ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]

这也有效并解决了问题。

>>> sorted(tlist, key=lambda t : (-t[1], t[2]), reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM