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

Fri*_*end 5 python terminal dictionary tuples list

这是我的问题,我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
Run Code Online (Sandbox Code Playgroud)

运行iam后收到错误消息

    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
Run Code Online (Sandbox Code Playgroud)

Vol*_*ity 16

key函数中指定参数sorted.

>>> tuple1=[(1, 3), (3, 2), (2, 1)]
>>> output = sorted(tuple1, key=lambda x: x[-1])
>>> print output
[(2, 1), (3, 2), (1, 3)]
Run Code Online (Sandbox Code Playgroud)

sorted功能(以及该list.sort方法)有一个可选的key它指定了对列表进行排序参数.

  • 如果你需要它以相反的顺序,你也可以添加`reverse`关键字:`output = sorted(tuple1,key = lambda x:x [-1],reverse = True)` (2认同)
  • @Friend这是最pythonic的方法,否则你应该依赖任何排序算法并自己实现,处理错误,效率等...你确定要这样做吗?(经验法则:不要重新发明轮子) (2认同)