为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯王 2023-01-04 10:12:17
我想要做的只是从日期值在特定月份内的列表中提取字典。from datetime import date, datetimelistexample = []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)
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

你可以尝试这样的事情:


from datetime import datetime

listexample=[]

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:")))


查看完整回答
反对 回复 2023-01-04
  • 1 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信