基于最后一个元素的Python元组排序
发布时间:2020-12-20 12:29:47  所属栏目:Python  来源:网络整理 
            导读:参见英文答案 Tuple pairs,finding minimum using python????????????????????????????????????3个 这是我的问题我有tuple1 = [(1,3),(3,2),(2,1)]我想根据每个元组的最后一个数字排序元组,所以结果将看起来像这样 输出= [(2,1),(1,3)] 下面是我的代码 i=0fo
                
                
                
            | 
                         
 参见英文答案 > 
 Tuple pairs,finding minimum using python????????????????????????????????????3个 
  
这是我的问题我有tuple1 = [(1,3),(3,2),(2,1)]我想根据每个元组的最后一个数字排序元组,所以结果将看起来像这样 输出= [(2,1),(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,1)])
  File "x.py",line 35,in sort_last
 if(y in x[len(x)-1]):
  TypeError: argument of type 'int' is not iterable
解决方法
 在sorted函数中指定key参数. 
  
  
  
        >>> tuple1=[(1,1)] >>> output = sorted(tuple1,key=lambda x: x[-1]) >>> print output [(2,3)] sorted函数(以及list.sort方法)有一个可选的key参数,用于指定对列表进行排序的内容. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
