Python natural sorting

后端 未结 2 1698
走了就别回头了
走了就别回头了 2020-11-27 06:49

I have some files that need to be sorted by name, unfortunately I can\'t use a regular sort, because I also want to sort the numbers in the string, so I did some research an

相关标签:
2条回答
  • 2020-11-27 07:19

    If you don't mind third party libraries, you can use natsort to achieve this.

    >>> import natsort
    >>> files = ['PresserInc-1.jpg', 'PresserInc-1_10.jpg', 'PresserInc-1_11.jpg', 'PresserInc-10.jpg', 'PresserInc-2.jpg', 'PresserInc-3.jpg', 'PresserInc-4.jpg', 'PresserInc-5.jpg', 'PresserInc-6.jpg', 'PresserInc-11.jpg']
    >>> natsort.natsorted(files)
    ['PresserInc-1.jpg',
     'PresserInc-1_10.jpg',
     'PresserInc-1_11.jpg',
     'PresserInc-2.jpg',
     'PresserInc-3.jpg',
     'PresserInc-4.jpg',
     'PresserInc-5.jpg',
     'PresserInc-6.jpg',
     'PresserInc-10.jpg',
     'PresserInc-11.jpg']
    
    0 讨论(0)
  • 2020-11-27 07:26

    Google: Python natural sorting.

    Result 1: The page you linked to.

    But don't stop there!

    Result 2: Jeff Atwood's blog that explains how to do it properly.

    Result 3: An answer I posted based on Jeff Atwood's blog.

    Here's the code from that answer:

    import re
    
    def natural_sort(l): 
        convert = lambda text: int(text) if text.isdigit() else text.lower() 
        alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] 
        return sorted(l, key=alphanum_key)
    

    Results for your data:

    PresserInc-1.jpg
    PresserInc-1_10.jpg
    PresserInc-1_11.jpg
    PresserInc-2.jpg
    PresserInc-3.jpg
    etc...
    

    See it working online: ideone

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