python排序字​​母数字列表,不使用orderdict

时间:2018-07-13 19:40:07

标签: python regex list sorting

我已经阅读了许多类似的问题,但是没有一个解决方案符合我的需求,即使用Python 2.6.6,并且没有安装或使用OrderedDict,如何才能根据列表中的第一个数字对列表进行排序每个项目?

这是我的列表:

apples = [ '15 The Green Apples ',
           '43 The Blue Apples ',
           '2 The Yellow Apples ',
           '7 The Red Apples ',
           '178 The Purple Apples '
         ]

apples.sort()给了我

[ '15 The Green Apples ',
  '178 The Purple Apples ',
  '2 The Yellow Apples ',
  '43 The Blue Apples ',
  '7 The Red Apples '
]

我想要的是:

[ '2 The Yellow Apples ',
  '7 The Red Apples ',
  '15 The Green Apples ',
  '43 The Blue Apples ',
  '178 The Purple Apples '
]

我试图将列表转换成字典,并给第一个数字15; 43; 2; 7; 178;但这没用。我知道为什么它是字符串形式的排序方式,但是我无法将其转换为整数。

我当时在考虑也许使用正则表达式,但是并没有走很远。

这会抢占数字中第一个空格之后的所有内容:

[^0-9]

这仅获取开头的数字:

[.0-9]

我认为可行的解决方案,但我不知道该怎么做,就是只使用正则表达式匹配数字并将其转换为整数,然后进行排序。

编辑:可能的重复问题具有不同的可接受的解决方案,不同的格式,但问题类似。

1 个答案:

答案 0 :(得分:4)

您必须指定一个自定义函数作为排序键,它将从每个字符串中提取初始数字

rest controller

或使用正则表达式

>>> apples.sort(key=lambda x: int(x.split()[0]))
>>> apples
['2 The Yellow Apples ', '7 The Red Apples ', '15 The Green Apples ', '43 The Blue Apples ', '178 The Purple Apples ']
>>>