How to sort a list of strings numerically?

前端 未结 14 2503
你的背包
你的背包 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:13

    You could pass a function to the key parameter to the .sort method. With this, the system will sort by key(x) instead of x.

    list1.sort(key=int)
    

    BTW, to convert the list to integers permanently, use the map function

    list1 = list(map(int, list1))   # you don't need to call list() in Python 2.x
    

    or list comprehension

    list1 = [int(x) for x in list1]
    

提交回复
热议问题