【发布时间】:2017-02-25 05:27:48
【问题描述】:
我有一个相当简单的列表(一个数字后跟一个句子),按正确的顺序排列:
-347 a negative number
-100 another negative number
-25 and again, a negative number
17 some text
25 foo bar
100 two same texts
100 two same texts (almost)
350 a positive number
每次添加新项目时,我都需要对该列表进行排序。
我搜索了 S.O.并找到了答案:
Sorting in python - how to sort a list containing alphanumeric values?
我使用的代码是怪异的,它是:
import re
def convert(str):
return int("".join(re.findall("\d*", str)))
list1.sort(key=convert)
为了更好地解释我的问题,我将列表打乱并运行代码。
结果是:
17 some text
-25 and again, a negative number
25 foo bar
100 two same texts (almost)
100 two same texts
-100 another negative number
-347 a negative number
350 a positive number
出了什么问题?自然对负数进行排序的代码的精度是多少?
【问题讨论】:
-
'-'不是数字,因此与'\d'不匹配。因此,您的模式匹配只会找到完整的数字。旁注:如果您的输入字符串是例如'1 this is line 00001',它将按您的键排序最后。''匹配'\d*',但int('')引发ValueError。 -
你可以在运行前将正负分开,然后将它们粘上,使负的反转并在顶部。
-
您可以将您的转换功能更改为
return int(str.split()[0])