gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:02:20 25 4
gpt4 key购买 nike

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

-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

出了什么问题?自然排序负数的代码的精度是多少?

最佳答案

排序可以接受元组,所以先按数字排序,再按后面的文字排序

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))

关于python - Python 中的字母数字排序和负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com