基于最后一个元素排序的Python元组

7

这里是我的问题。我有一个tuple1=[(1, 3), (3, 2), (2, 1)],我想根据每个元组的最后一位对元组进行排序,因此结果将如下所示:output=[(2, 1), (3, 2), (1, 3)]。以下是我的代码:

    i=0
for x in tuples:
    c.append(x[len(x)-1])
    last=sorted(c)
    for y in last.iteritems():
        if(y in x[len(x)-1]):
            print x             
            #b.insert(i,x)
i=i+1

运行后出现错误信息。

    Traceback (most recent call last):
    File "x.py", line 47, in <module>
   sort_last([(1, 3), (3, 2), (2, 1)])
  File "x.py", line 35, in sort_last
 if(y in x[len(x)-1]):
  TypeError: argument of type 'int' is not iterable

我的错,那个问题不是关于排序的,但解决方案是相同的:在 sortsorted 中指定 key 函数。 - Lev Levitsky
1个回答

26

sorted 函数中指定 key 参数。

>>> tuple1=[(1, 3), (3, 2), (2, 1)]
>>> output = sorted(tuple1, key=lambda x: x[-1])
>>> print output
[(2, 1), (3, 2), (1, 3)]

sorted函数(以及list.sort方法)有一个可选的key参数,它指定了列表排序的依据。


这个优雅的解决方案值得点赞。 - George
可以,它有效。但是有没有其他方法不使用“lambda”,而是使用for循环本身... - Friend
2
如果您需要按相反的顺序排序,也可以添加“reverse”关键字:output = sorted(tuple1, key=lambda x: x[-1], reverse=True) - drekyn
2
@朋友,这是最Pythonic的方法,否则你应该依赖于任何排序算法并自己实现,处理错误、效率等等... 你确定要这样做吗?(经验之谈:不要重复造轮子) - drekyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接