我如何进行以下排序?
import re
list_of_strings=['hulu_delta_20150528.xml', 'hulu_delta_20150524',
'playstation_full_20150529', 'hulu_full_20150528.xml']
sorted(list_of_strings, key=lambda x: (
x[:3],
re.search(r'\d{8}',x).group() if re.search(r'\d{8}',x) else None,
-x # How would this be done as a third criteria?
))
特别是,我如何按反向字母顺序排列项目作为第三个标准?最终结果应该是:
['hulu_delta_20150524', 'hulu_full_20150528.xml', 'hulu_delta_20150528.xml', 'playstation_full_20150529']
答案 0 :(得分:4)
您可以比较项目的负序数值,以按字母顺序进行比较:
# All hulu strings have same date
>>> list_of_strings=['hulu_delta_20150528.xml', 'hulu_delta_20150524',
'playstation_full_20150529', 'hulu_full_20150528.xml']
>>> files = sorted(list_of_strings, key=lambda x: (
x[:3],
re.search(r'\d{8}',x).group() if re.search(r'\d{8}', x) else None,
[-ord(c) for c in x]
))
>>> files
['hulu_delta_20150524', 'hulu_full_20150528.xml', 'hulu_delta_20150528.xml', 'playstation_full_20150529']