How to sort a list of strings numerically?

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

    I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:

    from natsort import natsorted # pip install natsort
    
    # Example list of strings
    a = ['1', '10', '2', '3', '11']
    
    [In]  sorted(a)
    [Out] ['1', '10', '11', '2', '3']
    
    [In]  natsorted(a)
    [Out] ['1', '2', '3', '10', '11']
    
    # Your array may contain strings
    [In]  natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
    [Out] ['string1', 'string3', 'string10', 'string11', 'string100']
    

    It also works for dictionaries as an equivalent of sorted. [1]: https://pypi.org/project/natsort/

提交回复
热议问题