打印特定值等于单独的指定标准的指定词典

我想要做的只是从日期值在特定月份内的列表中提取字典。


from datetime import date, datetime


listexample = []


def examplefunc():

  listexample.append(

    {'example_record':len(examplelist)+1,

     'date':datetime.strptime(input('Date (yyyy/mm/dd): ' ), '%Y/%m/%d'),

    })


examplefunc()


for i in listexample:

  print(listexample)

如果我将月份标准指定为“3”,则只有日期中的月份等于“3”的字典才会产生/打印。


如果我在请求输入时输入“2020/02/01”,输出解析为:[{'example_record': 4, 'date': datetime.datetime(2020, 2, 1, 0, 0)}]


月份在字典条目中(如上例中的“2”),但我只想提取那些“日期”为==特定月份(或当前月份)的字典条目。


我已经尝试遍历字典中指定键值的列表,但这似乎也不起作用。


这是我一直在尝试的示例:


def show_all_in_current_month():

while True: 

    (examplelist[0]['date']).month == '{:%m}'.format(date.today())

    for i in range(len(examplelist)):

      print(examplelist)

    break

任何帮助将不胜感激。谢谢!


编辑:这个(难以忍受的简单)解决方案适用于我的问题。谢谢大家的贡献。


for d in examplelist:

 if str(d['date'].month) == '2':

  print(d)


慕斯王
浏览 124回答 1
1回答

白衣染霜花

你可以尝试这样的事情:from datetime import datetimelistexample=[]def examplefunc():  listexample.append(    {'example_record':len(listexample)+1,     'date':datetime.strptime(input('Date (yyyy/mm/dd): ' ), '%Y/%m/%d'),    })#Define how many dates are you going to add for i in range(int(input("How many dates are you going to add?\n:"))):   examplefunc()def show_all_in_current_month(currentmonth):   #receives the a month and filter the dicts that are in that month   print([dict for dict in listexample if dict['date'].month==currentmonth])show_all_in_current_month(int(input("Which month do you want to filter the list with?\n:")))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python