我知道关于这种类型的排序有很多问题,我通过参考这些问题以及通过 repython 中的主题进行了多次尝试
re
我的问题是:
class Example(models.Model): _inherit = 'sorting.example' def unable_to_sort(self): data_list = ['Abigail Peterson Jan 25','Paul Williams Feb 1','Anita Oliver Jan 24','Ernest Reed Jan 28'] self.update({'list_of_birthday_week': ','.join(r for r in data_list)})
我需要sorted根据month&date喜欢:
sorted
month
date
data_list = ['Anita Oliver Jan 24','Abigail Peterson Jan 25','Ernest Reed Jan 28','Paul Williams Feb 1']
有什么办法可以做到这一点?
使用正则表达式提取日期而不是将其用作sorted函数的键。
import re pattern = r'(\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\D?(?:\d{1,2}\D?))' sort_by_date = lambda x: datetime.strptime(re.search(pattern, x).group(0), '%b %d') out = sorted(data_list, key=sort_by_date)
输出:
>>> out ['Anita Oliver Jan 24', 'Abigail Peterson Jan 25', 'Ernest Reed Jan 28', 'Paul Williams Feb 1']
输入:
>>> data_list ['Abigail Peterson Jan 25', 'Paul Williams Feb 1', 'Ernest Reed Jan 28', 'Anita Oliver Jan 24']