在类属性和今天的日期之后对字典进行排序

我有一个类 Reminder 和字典 Events,我想根据今天的日期对字典进行排序。


程序应该要求用户输入今天日期的 int 输入,然后打印字典中与这一天及以后相关的所有键。


例如。它不应该打印已经过去的事件。


   class Reminder:

    self.name = name

    self.date = date

    self.reminder = reminder 

    event1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')

    event2 = Reminder('to do next month', 20190401, 'get a job')

    event3 = Reminder('apply for college', 20190603, 'send in application'


    event_dict = {}

    event_dict[event1.name] = event1

    event_dict[event2.name] = event2

    event_dict[event3.name] = event3


    todays date = int(input("Input today's date!"))

所以现在当用户输入例如日期 20190328 时,程序不应该打印 event1,因为它已经过去了。


如前所述,我希望在打印之前对事件 2 和 3 进行排序,以便首先打印下一个即将到来的日期。


似乎没有必要对 2 个事件进行排序,但在整个代码中它将是更多的事件。


杨魅力
浏览 171回答 2
2回答

眼眸繁星

简单的实现:class Reminder:    def __init__(self, name, date, reminder):        self.name = name        self.date = date        self.reminder = reminder     def __str__(self):        return "Name: '{}' - Date: '{}' - Reminder: '{}'".format(self.name,                                                           self.date,                                                           self.reminder)event1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')event2 = Reminder('to do next month', 20190401, 'get a job')event3 = Reminder('apply for college', 20190603, 'send in application')event_dict = {}event_dict[event1.name] = event1event_dict[event2.name] = event2event_dict[event3.name] = event3todays_date = 20180101# implementationevents_sorted = sorted(event_dict.items(), key=lambda t: t[1].date)events = [e[1] for e in events_sorted if e[1].date >= todays_date]for e in events:    print(e)输出:Name: 'to do next month' - Date: '20190401' - Reminder: 'get a job'Name: 'apply for college' - Date: '20190603' - Reminder: 'send in application'

撒科打诨

class Reminder(object):    def __init__(self, name, date, reminder):        self.name = name        self.date = date        self.reminder = reminderevent1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')event2 = Reminder('to do next month', 20190401, 'get a job')event3 = Reminder('apply for college', 20190603, 'send in application')event_dict = {}    event_dict[event1.date] = event1    event_dict[event2.date] = event2    event_dict[event3.date] = event3todays_date = int(input("Input today's date!"))import operator#filter passed datesevent_dict = {k: v for k, v in event_dict.items() if k > todays_date}#sort dictionarysorted_events = sorted(event_dict.items(), key=operator.itemgetter(0))#print resultsfor item in sorted_events:    print("trip name: " , item[1].name, "| trip date: ", item[1].date, "| trip reminder: ", item[1].reminder,' \n')输出:trip name:  to do next month | trip date:  20190401 | trip reminder:  get a job  trip name:  apply for college | trip date:  20190603 | trip reminder:  send in application  
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python