Python Forum
sorting with numbers in text
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting with numbers in text
#2
Bruteforce-Method:

import re


def number_tuple(text: str) -> tuple[int]:
    """
    Return number pairs
    """
    return tuple(int(val) for val in re.split(r"\D+", text) if val)


items = ["AA33_43", "A", "A23", "B55", "1_1_4"]
sorted(items, key=number_tuple)
Output:
['A', '1_1_4', 'A23', 'AA33_43', 'B55']
A returns an empty tuple, so it's the first item.
(1, 1, 4) < (23,)
(23,) < (33, 42)
(33, 43) < (55,)
Skaperen and snippsat like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
sorting with numbers in text - by Skaperen - Jul-17-2021, 11:48 PM
RE: sorting with numbers in text - by DeaD_EyE - Jul-18-2021, 08:14 AM
RE: sorting with numbers in text - by snippsat - Jul-18-2021, 10:14 AM
RE: sorting with numbers in text - by Skaperen - Jul-19-2021, 10:30 PM
RE: sorting with numbers in text - by Skaperen - Jul-19-2021, 10:42 PM
RE: sorting with numbers in text - by Skaperen - Jul-20-2021, 01:15 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  reformatting text with comma separated numbers Skaperen 4 2,764 May-07-2020, 06:14 AM
Last Post: anbu23

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020