How to sort a list of strings numerically?

前端 未结 14 2046
你的背包
你的背包 2020-11-22 03:43

I know that this sounds trivial but I did not realize that the sort() function of Python was weird. I have a list of \"numbers\" that are actually in string for

相关标签:
14条回答
  • 2020-11-22 04:03

    You can also use:

    import re
    
    def sort_human(l):
        convert = lambda text: float(text) if text.isdigit() else text
        alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)]
        l.sort(key=alphanum)
        return l
    

    This is very similar to other stuff that you can find on the internet but also works for alphanumericals like [abc0.1, abc0.2, ...].

    0 讨论(0)
  • 2020-11-22 04:04

    Seamus Campbell's answer doesnot work on python2.x.
    list1 = sorted(list1, key=lambda e: int(e)) using lambda function works well.

    0 讨论(0)
  • 2020-11-22 04:08

    Python's sort isn't weird. It's just that this code:

    for item in list1:
       item=int(item)
    

    isn't doing what you think it is - item is not replaced back into the list, it is simply thrown away.

    Anyway, the correct solution is to use key=int as others have shown you.

    0 讨论(0)
  • 2020-11-22 04:08

    Try this, it’ll sort the list in-place in descending order (there’s no need to specify a key in this case):

    Process

    listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
    listC = sorted(listB, reverse=True) # listB remains untouched
    print listC
    

    output:

     [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]
    
    0 讨论(0)
  • 2020-11-22 04:09

    If you want to use strings of the numbers better take another list as shown in my code it will work fine.

    list1=["1","10","3","22","23","4","2","200"]
    
    k=[]    
    for item in list1:    
        k.append(int(item))
    
    k.sort()
    print(k)
    # [1, 2, 3, 4, 10, 22, 23, 200]
    
    0 讨论(0)
  • 2020-11-22 04:10

    The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.

    You have to CAST your input as an int instead:

    sorted strings:

    stringList = (1, 10, 2, 21, 3)

    sorted ints:

    intList = (1, 2, 3, 10, 21)

    To cast, just put the stringList inside int ( blahblah ).

    Again:

    stringList = (1, 10, 2, 21, 3)
    
    newList = int (stringList)
    
    print newList
    
    => returns (1, 2, 3, 10, 21) 
    
    0 讨论(0)
提交回复
热议问题