【问题标题】:Python tuples sorting based on last element [duplicate]基于最后一个元素的Python元组排序[重复]
【发布时间】:2013-01-27 13:37:18
【问题描述】:

这是我的问题,我有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

运行 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

【问题讨论】:

  • 我的错,这个问题与排序无关,但解决方案是相同的:将key 函数指定为sortsorted

标签: python list dictionary terminal tuples


【解决方案1】:

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 参数,用于指定列表的排序依据。

【讨论】:

  • 这个优雅的解决方案+1。
  • 是的,它可以工作..但是有没有其他方法不使用'lambda'我的意思是使用for循环本身......
  • 如果需要逆序也可以添加reverse关键字:output = sorted(tuple1, key=lambda x: x[-1], reverse=True)
  • @Friend 这是最pythonic的方法,否则你应该依赖任何排序算法并自己实现它,处理错误,效率等......你确定你想做吗那? (经验法则:不要重新发明轮子)
猜你喜欢
  • 2023-03-18
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多