Alphanumeric sorting in Python and negative numbers

只谈情不闲聊 提交于 2021-01-27 06:53:41

问题


I have a fairly simple list (a number followed by a sentence), here in the right order:

-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

I need to sort that list each time a new item is added.

I searched S.O. and found that answer :

Sorting in python - how to sort a list containing alphanumeric values?

The code I used is freakish’s, which goes :

import re
def convert(str):
    return int("".join(re.findall("\d*", str)))

list1.sort(key=convert)

In order to better explain my problem, I shuffled the list and ran the code.

The result was :

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

What went wrong ? What is the precision in the code that would sort naturally the negative numbers?


回答1:


The easiest approach, IMHO, would be to split the string to individual words, and then sort by the first word converted to an int:

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

EDIT:
As Keatinge, the above solution won't properly handle two strings that start with the same number. Using the entire string as a secondary search term should solve this issue:

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



回答2:


Sort can accept a tuple, so first sort by the number, then by the text after

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


来源:https://stackoverflow.com/questions/42448265/alphanumeric-sorting-in-python-and-negative-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!