我想编写一个日历,第一个列表是日期,第二个是事件。我希望您必须输入一个日期,如果它在日历列表中,我希望我的代码搜索它在列表中的位置。然后,我的代码应该在同一位置搜索事件列表中的内容并打印事件。感谢每一个安塞。
附言我用python编码了几个星期,所以我仍然是一个菜鸟
calendar = ['01.02.2019', '02.02.2019']
termine = ['15:20 playing football', '17:30 playing basketball']
date = str(input('Date: '))
if (date in calendar):
print ('found');
esindices = [i for i, x in enumerate(calendar) if x == date]
print (esindices)
print(events[int(esindices)])
日期: 01.02.2019发现[0]
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-17-00e8535c4c6c> in <module> 8 esindices = [i for i, x in enumerate(calendar) if x == date] 9 print (esindices) ---> 10 print(events[int(esindices)]) NameError: name 'events' is not defined
这是出现的错误,我不知道如何解决这个问题。
你会得到一个NameError
- 这意味着python不知道什么。这通常是一个范围问题,或者有时您忘记创建变量(或变量名中有拼写错误)。
对于调试,您可以注释掉出错的行并print()
...要查看可能出现的问题 - 您可以阅读更多有关调试的提示:您能否逐步执行 python 代码来帮助调试问题?
故障:
您的代码具有termine
- 不是events
,并且使用了德语,英语和西班牙语(?)的疯狂混合。
修复:
calendar = ['01.02.2019', '02.02.2019']
termine = ['15:20 playing football', '17:30 playing basketball']
date = str(input('Date: '))
if (date in calendar):
print ('found')
esindices = [i for i, x in enumerate(calendar) if x == date]
print (esindices)
for index in esindices: # this is a list, not a single index - you need to iterate over
print(termine[index]) # fix naming
最好
使用字典 - 您可以使用实际日期作为键,并使用要做的事情列表作为值:
import datetime
# your calender dictionary
cal = {}
# today
dt = datetime.date.today()
# put in some values
for i in range(5):
cal[dt-datetime.timedelta(days=i)] = [f"look {i} vids"]
# print default values
print(cal)
输出:
# defaults
{datetime.date(2019, 1, 19): ['look 0 vids'],
datetime.date(2019, 1, 18): ['look 1 vids'],
datetime.date(2019, 1, 17): ['look 2 vids'],
datetime.date(2019, 1, 16): ['look 3 vids'],
datetime.date(2019, 1, 15): ['look 4 vids']}
输入更多数据:
# get input, split input
datestr,action = input("Date:action").split(":") # 2018-01-25:Read a book
# make datestr into a real date
date = datetime.datetime.strptime(datestr.strip(),"%Y-%m-%d").date()
# create key if needed, append action to list (use a defaultdict - it is faster then this)
# if you feel you hit a speed-problem and want it to be more "optiomal"
cal.setdefault(date,[]).append(action)
# input another date:action
datestr,action = input("Date:action").split(":") # 2018-01-25:Go out and party
# parse the date again
date = datetime.datetime.strptime(datestr.strip(),"%Y-%m-%d").date()
# this time the key exists and we add to that one
cal.setdefault(date,[]).append(action)
# print all
print(cal)
输出:
# after inputs:
{datetime.date(2019, 1, 19): ['look 0 vids'],
datetime.date(2019, 1, 18): ['look 1 vids'],
datetime.date(2019, 1, 17): ['look 2 vids'],
datetime.date(2019, 1, 16): ['look 3 vids'],
datetime.date(2019, 1, 15): ['look 4 vids'],
datetime.date(2018, 1, 25): ['Read a book', 'Go out and party']}
Doku: dict.setdefault