Python中的字母数字排序和负数

时间:2017-02-24 21:06:07

标签: python sorting

我有一个相当简单的列表(一个数字后跟一个句子),这里的顺序正确:

-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

出了什么问题?代码的精确度是什么,它会自然地对负数进行排序?

2 个答案:

答案 0 :(得分:6)

排序可以接受元组,因此首先按数字排序,然后按

之后的文本排序
list_text = """-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"""

list1 = list_text.split("\n")

list1.sort(key=lambda x: (int(x.split()[0]), x.split(" ",1)))

print("\n".join(list1))

答案 1 :(得分:3)

最简单的方法是恕我直言,将字符串拆分为单个单词,然后按照转换为int的第一个单词排序:

list1.sort(key = lambda x : int(x.split(" ")[0]))

修改:
作为Keatinge,上述解决方案无法正确处理以相同数字开头的两个字符串。使用整个字符串作为辅助搜索词可以解决此问题:

list1.sort(key = lambda x : (int(x.split(" ")[0]), x)