简体   繁体   中英

Sort a python list of strings with a numeric number

I have a list of filenames called filelist

 In []: filelist
Out []: ['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']

I want to sort this filelist by the numerical value that is in the bolded position

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

So in this example, the output would be

Out []: ['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']

Thank you!

import re

f = lambda s: int(re.findall(r'.*RAID6-(\d+).*', s)[0])
sorted(l, key=f)

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']

Use a regex to parse out the number and use that as a sort key.

Quick and dirty:

import re

l = ['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 get_sort_number(s):
    pattern = r'C:\\Mon\d+\\P-2NODE-RAID6-(\d+)'

    try:
        return int(re.match(pattern, s).group(1))
    except AttributeError:
        return 0

sorted(l, key=get_sort_number)

This gives

['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']

All strings that cannot be matched by the regex would be at the beginning of the sorted list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM