2013-02-12 105 views
1

这里是我的问题,我有tuple1=[(1, 3), (3, 2), (2, 1)]我想根据每个元组这样的结果会是这样 output=[(2, 1), (3, 2), (1, 3)]低于 的最后一位数字进行排序元组是我的代码Python的元组排序基于最后一个元素上

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 
+0

我的不好,这个问题不是关于排序,但解决方案是相同的:指定“键”功能,以“排序”或“排序”。 – 2013-02-12 09:32:06

回答

10

指定在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指定什么对列表进行排序。

+0

+1这个优雅的解决方案。 – George 2013-02-12 09:34:19

+0

y它的工作原理..但是有没有其他方法没有使用'拉姆达'我的意思是使用循环本身.... – Friend 2013-02-12 09:48:56

+2

如果你需要它倒序,你还可以添加'reverse'关键字:'output = sorted( tuple1,key = lambda x:x [-1],reverse = True)' – drekyn 2013-02-12 09:49:28

相关问题