我想以.log应该是第一个文件,.gz文件应该是降序的方式对列表进行排序
my_list = [
'/abc/a.log.1.gz',
'/abc/a.log',
'/abc/a.log.gz',
'/abc/a.log.30.gz',
'/abc/a.log.2.gz',
'/abc/a.log.5.gz',
'/abc/a.log.3.gz',
'/abc/a.log.6.gz',
'/abc/a.log.4.gz',
'/abc/a.log.12.gz',
'/abc/a.log.10.gz',
'/abc/a.log.8.gz',
'/abc/a.log.14.gz',
'/abc/a.log.29.gz'
]
预期结果:
my_list = ['/abc/a.log',
'/abc/a.log.gz',
'/abc/a.log.30.gz',
'/abc/a.log.29.gz',
'/abc/a.log.29.gz',
'/abc/a.log.14.gz',
'/abc/a.log.12.gz',
'/abc/a.log.10.gz',
'/abc/a.log.8.gz',
'/abc/a.log.6.gz',
'/abc/a.log.5.gz',
'/abc/a.log.4.gz',
'/abc/a.log.3.gz',
'/abc/a.log.2.gz'
'/abc/a.log.1.gz']
我的解决方案: 导入操作系统
def get_sort_keys(filepath):
split_file_path = os.path.splitext(filepath)
sort_key = (split_file_path[1], *os.path.splitext(split_file_path[0]))
return (sort_key[0], sort_key[1], int(sort_key[2].strip(".")) if sort_key[2] else 0)
print(sorted(my_list, key=get_sort_keys, reverse=True))
获取错误:
ValueError: invalid literal for int() with base 10: 'log'
答案 0 :(得分:2)
您可以将sorted
与自定义函数一起使用,该函数可以执行一些“试一试”检查。
def try_convert(x):
y = x.rsplit('.', 2)[-2]
return ('log' not in x, int(y) if y.isdigit() else float('inf'), x)
sorted(my_list, key=try_convert, reverse=True)
['/abc/a.log.gz',
'/abc/a.log',
'/abc/a.log.30.gz',
'/abc/a.log.29.gz',
'/abc/a.log.14.gz',
'/abc/a.log.12.gz',
'/abc/a.log.10.gz',
'/abc/a.log.8.gz',
'/abc/a.log.6.gz',
'/abc/a.log.5.gz',
'/abc/a.log.4.gz',
'/abc/a.log.3.gz',
'/abc/a.log.2.gz',
'/abc/a.log.1.gz']
该函数确保不带整数部分的文件名最后排序(如果按降序排序,则为第一个)。此外,所有“ .log”文件都位于第一位。
答案 1 :(得分:1)
您正在尝试将字符串'log'
传递到int()
中。
然后无法将其转换为int
并引发ValueError: invalid literal for int() with base 10: 'log'
这是在return (sort_key[0], sort_key[1], int(sort_key[2].strip(".")) if sort_key[2] else 0)
尝试在转换中使用try catch块
答案 2 :(得分:1)
或使用:
>>> sorted(my_list,key=lambda x: int(x.split('.')[2]) if x.split('.')[2].isdigit() else 31,reverse=True)
['/abc/a.log.gz', '/abc/a.log.30.gz', '/abc/a.log.29.gz', '/abc/a.log.14.gz', '/abc/a.log.12.gz', '/abc/a.log.10.gz', '/abc/a.log.8.gz', '/abc/a.log.6.gz', '/abc/a.log.5.gz', '/abc/a.log.4.gz', '/abc/a.log.3.gz', '/abc/a.log.2.gz', '/abc/a.log.1.gz']
>>>
更新的问题:
>>> sorted(my_list,key=lambda x: int(x.split('.')[-2]) if x.split('.')[-2].isdigit() else 31,reverse=True)
['/abc/a.log', '/abc/a.log.gz', '/abc/a.log.30.gz', '/abc/a.log.29.gz', '/abc/a.log.14.gz', '/abc/a.log.12.gz', '/abc/a.log.10.gz', '/abc/a.log.8.gz', '/abc/a.log.6.gz', '/abc/a.log.5.gz', '/abc/a.log.4.gz', '/abc/a.log.3.gz', '/abc/a.log.2.gz', '/abc/a.log.1.gz']
>>>