python排序不带ordereddict的字母数字列表
我读过很多类似的问题,但没有一个解决方案符合我的要求,即使用Python 2.6.6,在没有安装或使用OrderedICT的情况下,如何根据每个项目中的第一个数字对列表进行排序 这是我的清单:python排序不带ordereddict的字母数字列表,python,regex,list,sorting,Python,Regex,List,Sorting,我读过很多类似的问题,但没有一个解决方案符合我的要求,即使用Python 2.6.6,在没有安装或使用OrderedICT的情况下,如何根据每个项目中的第一个数字对列表进行排序 这是我的清单: apples = [ '15 The Green Apples ', '43 The Blue Apples ', '2 The Yellow Apples ', '7 The Red Apples ', '178 T
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; 但那没用。我理解为什么它是这样排序的,因为它是一个字符串,但我不能将它转换成int
我想也许用正则表达式,但没走多远
这将捕获数字中第一个空格后的所有内容:
[^0-9]
这只获取开头的数字:
[.0-9]
我认为有一个解决方案是可行的,但我不知道如何做到这一点,就是只使用正则表达式匹配数字,并将其转换为int,然后按这种方式排序
编辑:可能重复的问题有不同的可接受解决方案、不同的格式,但问题类似。您必须指定一个自定义函数作为排序键,它将从每个字符串中提取初始数字
>>> 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 ']
>>>
或者使用正则表达式
>>> import re
>>> apples.sort(key=lambda x: int(re.findall('\d+', x)[0]))
>>> apples
['2 The Yellow Apples ', '7 The Red Apples ', '15 The Green Apples ', '43 The Blue Apples ', '178 The Purple Apples ']
>>>
您必须指定一个自定义函数作为排序键,它将从每个字符串中提取初始数字
>>> 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 ']
>>>
或者使用正则表达式
>>> import re
>>> apples.sort(key=lambda x: int(re.findall('\d+', x)[0]))
>>> apples
['2 The Yellow Apples ', '7 The Red Apples ', '15 The Green Apples ', '43 The Blue Apples ', '178 The Purple Apples ']
>>>
要仅匹配数字,请使用
\d+
。在python中转换为int非常简单,只需使用int(something)
sorted(apples,key=lambda x:int(x.split()[0])
来匹配数字即可使用\d+
。在python中转换为int就像int(something)
sorted(apples,key=lambda x:int(x.split()[0])一样简单。
这正是我想要的,谢谢。。。现在出于好奇,如何将排序从升序改为降序?您可以传递额外的关键字参数reverse=True
。请参阅列表的文档。这里的sort
方法:另一种方法是简单地对值求反:key=lambda x:-int(x.split()[0])
。这正是我想要的,谢谢。。。现在出于好奇,如何将排序从升序改为降序?您可以传递额外的关键字参数reverse=True
。请参阅列表的文档。这里的sort
方法:另一种方法是简单地对值求反:key=lambda x:-int(x.split()[0])
。