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

前端 未结 2 384
醉梦人生
醉梦人生 2020-12-03 08:42

I have a list that consists of details like this:

list1 = [\"1\", \"100A\", \"342B\", \"2C\", \"132\", \"36\", \"302F\"]

now, i want to sor

相关标签:
2条回答
  • 2020-12-03 09:09

    You want to use natural sort:

    import re
    
    _nsre = re.compile('([0-9]+)')
    def natural_sort_key(s):
        return [int(text) if text.isdigit() else text.lower()
                for text in re.split(_nsre, s)]   
    

    Example usage:

    >>> list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]
    >>> list1.sort(key=natural_sort_key)
    >>> list1
    ['1', '2C', '36', '100A', '132', '302F', '342B']
    

    This functions by splitting the elements into lists separating out the numbers and comparing them as integers instead of strings:

    >>> natural_sort_key("100A")
    ['', 100, 'a']
    >>> natural_sort_key("342B")
    ['', 342, 'b']
    

    Note that this only works in Python3 if you are always comparing ints with ints and strings with strings, otherwise you get a TypeError: unorderable types exception.

    0 讨论(0)
  • 2020-12-03 09:09

    Well, you have to find a way to convert your strings to numbers first. For example

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

    and then you use it as a sort key:

    list1.sort(key=convert)
    
    0 讨论(0)
提交回复
热议问题