如何对包含数字的 glob.glob 进行排序?

How to sort glob.glob containing numbers?

正在做

glob.glob('/var/log/apache2/other_vhosts_access.log*')

给出一个未排序的列表,例如 ['....76.gz', '....16.gz', '....46.gz', ...]。另外,

sorted(glob.glob('/var/log/apache2/other_vhosts_access.log*')) 

给予

other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
...
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz

如何排序更好? .log, .log.1, .log.2.gz, ..., .log.9.gz, .log.10.gz, ...

为了扩展我的评论,也许像这样的事情就可以了。这将提取在小数点之间或文件末尾找到的第一个数字序列,并将该值用作主要排序键,并使用完整文件名作为次要排序键。

file_list = """
other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz
""".strip().split()

import re

re_num = r"\.(\d+)(\.|$)"

def sort_key(file_name):
    match=re.search(re_num,file_name)
    if match is None:
        return(0,file_name)
    else:
        return(int(match.group(1)),file_name)
    
print(*sorted(file_list,key=sort_key),sep='\n')

基于Is there a built in function for string natural sort?,这里是一个单行解决方案:

natsort = lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split('(\d+)', s)]

sorted(glob.glob('/var/log/apache2/other_vhosts_access.log*'), key=natsort)