基于最后一个元素的Python元组排序
问题内容:
这个问题已经在这里有了答案 :
元组对,使用python查找最小值 (3个答案)
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
运行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
函数中指定参数sorted
。
>>> 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
参数,用于指定要对列表进行排序的内容。