【问题标题】:How to sort a list of lists according to list item which is a number represented as string in python?如何根据列表项对列表列表进行排序,列表项是python中表示为字符串的数字?
【发布时间】:2013-01-19 12:22:08
【问题描述】:

我有 3 个列表:

>>> a = ["12", "a"]
>>> b = ["123", "b"]
>>> c = ["4", "c"]

我将它们放在一个新列表中:

>>> d = [a,b,c]

当我根据每个内部列表的第一项对它们进行排序时:

>>> sorted(d, key=itemgetter(0))
[['12', 'a'], ['123', 'b'], ['4', 'c']]

但我想要:

[['4', 'c'], ['12', 'a'], ['123', 'b']]

另外,第一项可能有前导零:

>>> a = ["012", "a"]
>>> b = ["0123", "b"]
>>> c = ["04", "c"]

再次,我想以这种方式查看排序列表:

[['04', 'c'], ['012', 'a'], ['0123', 'b']]

我该怎么做?

【问题讨论】:

    标签: python string list sorting


    【解决方案1】:

    只需在 key getter 中使用int()

    In [5]: sorted(d, key=lambda x:int(x[0]))
    Out[5]: [['4', 'c'], ['12', 'a'], ['123', 'b']]
    

    在第二个例子中:

    In [10]: sorted(d, key=lambda x:int(x[0]))
    Out[10]: [['04', 'c'], ['012', 'a'], ['0123', 'b']]
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 2014-06-13
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多