def command_add(date, event, calendar):
if date not in calendar:
calendar[date] = list()
calendar[date].append(event)
calendar = {}
command_add("2015-10-29", "Python class", calendar)
command_add("2015-10-12", "Eye doctor", calendar)
command_add("2015-10-12", "lunch with sid", calendar)
command_add("2015-10-29", "Change oil in blue car", calendar)
command_add("2015-10-29", "test car", calendar)
print(calendar)
def command_show(calendar):
for (date, event) in sorted(calendar.items()):
print(date+':')
for i in enumerate(event):
print(' '+str(i[0])+': '+i[1])
command_show(calendar)
def command_delete(date, entry_number, calendar):
for (date, event) in sorted(calendar.items()):
for i in enumerate(event):
del i[entry_number]
def command_delete(date, entry_number, calendar):
for (date, event) in sorted(calendar.items()):
for i in enumerate(event):
i.remove(entry_number)
command_delete("2015-10-29", 2, calendar)
command_show(calendar)
我尝试了这两种方法,但我似乎无法弄清楚如何访问事件以删除日期上的特定事件 对command_delete的调用应删除command_add函数的第3个条目,因为它从0开始计数
错误我得到的元组对象不支持删除项目或删除
答案 0 :(得分:0)
根据我对您的代码的初步评论:
我可以看到许多问题; e.g。 0)两个函数的名称为command_delete
。
1)在command_delete
函数中:
1.1)日期参数被覆盖,因此丢失。
1.2)检查日期参数匹配的代码在哪里?即日期参数未使用。
1.3)为什么要对日历进行排序?
1.4)enumerate
返回一个元组:ie(0,event [0]),(1,event 1),(2,event [2]),...这意味着我是一个元组,是不可变的。令人惊讶的是,在command_show
中,你正确使用它作为元组,而不是在这里。
2)command_add
函数中的缩进错误
现在尝试使用此
from collections import defaultdict
def command_add(date, event, calendar):
calendar[date].append(event)
def command_show(calendar):
for date, event in sorted(calendar.items()):
print(date+':')
for i, el in enumerate(event):
print(' {}: {}'.format(i, el))
def command_delete(date, entry_number, calendar):
events = calendar.get(date)
if events:
del events[entry_number]
calendar = defaultdict(list)
command_add("2015-10-29", "Python class", calendar)
command_add("2015-10-12", "Eye doctor", calendar)
command_add("2015-10-12", "lunch with sid", calendar)
command_add("2015-10-29", "Change oil in blue car", calendar)
command_add("2015-10-29", "test car", calendar)
command_show(calendar)
print('now lets delete the "test car" appointment')
command_delete("2015-10-29", 2, calendar)
command_show(calendar)
产生
2015-10-12:
0: Eye doctor
1: lunch with sid
2015-10-29:
0: Python class
1: Change oil in blue car
2: test car
now lets delete the "test car" appointment
2015-10-12:
0: Eye doctor
1: lunch with sid
2015-10-29:
0: Python class
1: Change oil in blue car
请花点时间研究defaultdict
的行为,例如PMOTW