How to sort a list of strings numerically?

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

    Simple way to sort a numerical list

    numlists = ["5","50","7","51","87","97","53"]
    results = list(map(int, numlists))
    results.sort(reverse=False)
    print(results)
    
    0 讨论(0)
  • 2020-11-22 04:30

    real problem is that sort sorts things alphanumerically. So if you have a list ['1', '2', '10', '19'] and run sort you get ['1', '10'. '19', '2']. ie 10 comes before 2 because it looks at the first character and sorts starting from that. It seems most methods in python return things in that order. For example if you have a directory named abc with the files labelled as 1.jpg, 2.jpg etc say up to 15.jpg and you do file_list=os.listdir(abc) the file_list is not ordered as you expect but rather as file_list=['1.jpg', '11.jpg'---'15.jpg', '2.jpg]. If the order in which files are processed is important (presumably that's why you named them numerically) the order is not what you think it will be. You can avoid this by using "zeros" padding. For example if you have a list alist=['01', '03', '05', '10', '02','04', '06] and you run sort on it you get the order you wanted. alist=['01', '02' etc] because the first character is 0 which comes before 1. The amount of zeros padding you need is determined by the largest value in the list.For example if the largest is say between 100 and 1000 you need to pad single digits as 001, 002 ---010,011--100, 101 etc.

    0 讨论(0)
提交回复
热议问题