1

我有 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']]

我怎样才能做到这一点?

4

1 回答 1

6

只需int()在 key getter 中使用:

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']]
于 2013-01-19T12:24:52.453 回答