Python Alphanumeric Sort and Negative Numbers

I have a pretty simple list (a number followed by a sentence), here in the correct 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 this list every time a new item is added.

I searched for SO and found the answer:

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

The code I used is the quirks that go:

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

list1.sort(key=convert)

To better explain my problem, I shuffled the list and ran the code.

The result is:

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

Something went wrong? What is the accuracy of code that would naturally sort negative numbers?

+4
source share
2 answers

, IMHO, , , , int:

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

EDIT:
Keatinge, , . :

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

, ,

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

Source: https://habr.com/ru/post/1670788/


All Articles