【问题标题】:Sorting list of lists with mixed numerical values具有混合数值的列表的排序列表
【发布时间】:2011-04-09 14:40:50
【问题描述】:

场景:列表包含具有各种值的列表记录的“行”

问题:List.sort 没有将数值考虑在内,因此值最终会出现在各处

即 9 出现在 80 之后的列表中

我尝试过使用

list.sort(key=operator.itemgetter[index])

做一个

list.sort(lambda x,y:int(x[index])<int(y[index])) 

无济于事。

【问题讨论】:

  • 列表中的值是什么 - 我们需要更多信息

标签: python list sorting numbers


【解决方案1】:

使用转换后的数字作为键。

L.sort(key=lambda x: int(x[index]))

【讨论】:

    【解决方案2】:

    你在正确的轨道上,但是 operator.itemgetter 是一个函数,所以语法是:

    list.sort(key=operator.itemgetter(index))
    

    或者,使用 lambda:

    list.sort(key=lambda x: x[index])
    

    key 参数是要走的路,cmp 参数在 Python 3 中已被移除。如果你还是想使用它,你应该使用 cmp() 实现比较器的内置函数:

    list.sort(cmp=lambda x, y: cmp(x[index], y[index]))
    

    另请参阅:http://wiki.python.org/moin/HowTo/Sorting/

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2014-08-18
      • 2021-12-12
      相关资源
      最近更新 更多