python list基于日期存在的字典排序

时间:2018-02-20 10:48:30

标签: python dictionary

我有一个如下列表:

lst = [{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'}, {'dt': u'NA'}, {'dt': u'December 1st'}, {'dt': u'Feb 1, 2018'}, {'dt': u'January 31'}, {'dt': u'Oct 31, 2017'}, {'dt': u'July 11'}, {'dt': u'Jan 22, 2018'},{'dt': u'Thursday'}]

lst.sort(key=lambda item:item['dt'], reverse=True)
print lst

[{'dt': u'Thursday'}, {'dt': u'Oct 31, 2017'}, {'dt': u'NA'}, {'dt': u'July 11'}, {'dt': u'January 31'}, {'dt': u'Jan 22, 2018'}, {'dt': u'Feb 1, 2018'}, {'dt': u'December 1st'}, {'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'}]

但我的输出应该如下所示。

[{'dt': u'Feb 1, 2018'},{'dt': u'Jan 22, 2018'},{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'},{'dt': u'Oct 31, 2017'},{'dt': u'December 1st'},{'dt': u'July 11'}, {'dt': u'January 31'},{'dt': u'Thursday'},{'dt': u'NA'}]

元素应按以下顺序排序:

  • 第一个字符串(显示为过去)
  • 那些只有(12月到1月)的
  • 然后使用'NA'

2 个答案:

答案 0 :(得分:1)

如果您更具体地了解您的抓取日期是如何格式化的,可以稍微清理一下答案:

from i in entities.Table1.AsNoTracking().Where(i => (i.IsDeleted == false))
                    join se in entities.Table2.AsNoTracking() on i.Id equals se.SId
                    join set in entities.Table3.AsNoTracking().Where(i => (i.Name == "Attribute1" && i.Value.Contains("F"))
                                                                              && (i.Name == "Atrribute2" && i.Value.Contains("S")))
                                                                              on i.Id equals set.SId
                    select new
                    {
                        Name = i.Name,
                        Id = i.Id
                    };

答案 1 :(得分:1)

以下是针对您的问题的另一个 硬编码 解决方案:

from datetime import datetime
import calendar
import re

def datesort(item):
    item = re.sub('st|nd|rd|th', '', item['dt'])
    try:
        return datetime.strptime(item, '%b %d, %Y')
    except ValueError:
        try:
            return datetime.strptime(item + ', 1903', '%b %d, %Y')
        except ValueError:
            try:
                return datetime.strptime(item + ', 1903', '%B %d, %Y')
            except ValueError:
                try:
                    return datetime(1902, 1, list(calendar.day_name).index(item) + 1)
                except ValueError:
                    return datetime(1901,1,1)

lst = [{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'}, {'dt': u'NA'}, {'dt': u'December 1st'}, {'dt': u'Feb 1, 2018'}, {'dt': u'January 31'}, {'dt': u'Oct 31, 2017'}, {'dt': u'July 11'}, {'dt': u'Jan 22, 2018'},{'dt': u'Thursday'}]

sorted(lst, key=datesort, reverse=True)
#[{'dt': u'Feb 1, 2018'},{'dt': u'Jan 22, 2018'},{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'},{'dt': u'Oct 31, 2017'},{'dt': u'December 1st'},{'dt': u'July 11'}, {'dt': u'January 31'},{'dt': u'Thursday'},{'dt': u'NA'}]