我想使用完整匹配或前缀匹配的列表返回已排序的列表。我可以演示一个仅使用完整匹配的函数sorted_schedule
。
# This is the defined order (CONSTANT)
WEEKDAY_ORDER = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
# This is my working function
def sorted_schedule(s):
return sorted(s, key=lambda k: WEEKDAY_ORDER.index(k))
# Given an unordered set, return a sorted list
schedule1 = set(['Wednesday', 'Friday'])
print(schedule1) # set(['Friday', 'Wednesday'])
print(sorted_schedule(schedule1)) # ['Wednesday', 'Friday']
但是,它不适用于前缀匹配 - 也就是说,开头是weekday_order
中的匹配项,但项目的其余部分无关紧要。
schedule2 = set(['Wednesday afternoon', 'Friday'])
print(sorted_schedule(schedule2))
# ValueError: 'Wednesday afternoon' is not in list
我猜我需要为key
提供不同的功能,但我不确定如何制作此功能。
答案 0 :(得分:1)
取字符串的第一部分。 (Wednesday
)Wednesday afternoon
>>> WEEKDAY_ORDER = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>>
>>> def sorted_schedule(s):
... return sorted(s, key=lambda k: WEEKDAY_ORDER.index(k.split()[0])) # <---
...
>>> schedule2 = set(['Wednesday afternoon', 'Friday'])
>>> print(sorted_schedule(schedule2))
['Wednesday afternoon', 'Friday']