Sort a python list of strings with a numeric number

前端 未结 3 767
夕颜
夕颜 2021-01-29 06:57

I have a list of filenames called filelist

 In []: filelist
Out []: [\'C:\\\\Mon20412\\\\P-2NODE-RAID6-1BLACK-32k-100-segmented.xlsx\',
                 


        
3条回答
  •  无人共我
    2021-01-29 07:32

    Find a good, reliable way to extract the number that you want. Then sort by that number, using the key argument. This seems to be reliable enough for your input, but it's not efficient.

    a = ['C:\\Mon20412\\P-2NODE-RAID6-1BLACK-32k-100-segmented.xlsx',
        'C:\\Mon25312\\P-2NODE-RAID6-13RED-32k-100-segmented.xlsx',
        'C:\\Mon20362\\P-2NODE-RAID6-2GREEN-32k-100-segmented.xlsx']
    
    def k(a):
        x = a.split("\\")[-1].split("-")[3]
        y = filter(lambda x: x in "0123456789", x)
        return int("".join(list(y)))
    
    
    print(sorted(a, key=k))
    

    output:

    ['C:\\Mon20412\\P-2NODE-RAID6-1BLACK-32k-100-segmented.xlsx', 
    'C:\\Mon20362\\P-2NODE-RAID6-2GREEN-32k-100-segmented.xlsx',
    'C:\\Mon25312\\P-2NODE-RAID6-13RED-32k-100-segmented.xlsx']
    

提交回复
热议问题