每次运行以下代码时,都会出现错误“ TypeError:'set'对象不支持索引”
import datetime
now = datetime.datetime.now()
y = now.year
days_in_month_dict = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
last_day = last_day + (days_in_month_dict[month2 - 1] - day2)
days = days - last_day
return days
print daysBetweenDates(1900,1,1,1999,12,31)
完整错误消息:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/a212440163/PycharmProjects/udas/numero.py
Traceback (most recent call last):
File "/Users/a212440163/PycharmProjects/udas/numero.py", line 57, in <module>
print daysBetweenDates(1900,1,1,1999,12,31)
File "/Users/a212440163/PycharmProjects/udas/numero.py", line 44, in daysBetweenDates
last_day = last_day + (days_in_month_dict[month2 - 1] - day2)
TypeError: 'set' object does not support indexing
Process finished with exit code 1
答案 0 :(得分:2)
尽管它们的语法和某些语义相似,但是您有一个集合,而不是字典。字典包含键和值,而您无法为您提供键。而是添加月份数字以将其转换为适当的字典,然后按月份编制索引:
days_in_month_dict = { 1:31,2:28,3:31,4:30,5:31,6:30, 7:31,8:31,9:30,10:31,11:30,12:31}
last_day = last_day +(days_in_month_dict [month2]-day2)
答案 1 :(得分:0)
在您的代码中,days_in_month_dict
不是dict
,而是set
对象。集合不支持索引,因为它们是无序的。
尝试:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
last_day = last_day + (days_in_month[month2 - 1] - day2)
答案 2 :(得分:0)
在这里,您尝试在特定索引(索引)处访问集合中的元素。像字典一样,集合也不支持索引。
days_in_month_dict [month2-1-
如果您将集合更改为列表: [31,28,31,30,31,30,31,31,30,31,30,31]
您将可以通过索引访问元素
答案 3 :(得分:0)
您正在尝试使用索引来访问集合。集合不支持索引。您想要的是列表。
使用方括号代替大括号。
a = [1, 2, 3] # This is a list
b = {1, 2, 3} # This is a set
print(a[0])
print(b[1])
输出:
1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing