How to sort a list of strings numerically?

前端 未结 14 2486
你的背包
你的背包 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条回答
  •  闹比i
    闹比i (楼主)
    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) 
    

提交回复
热议问题