[英]How to solve TypeError: 'int' object has no attribute '__getitem__'?
I have written the following code, but it fails with the error message TypeError: 'int' object has no attribute '__getitem__'
at line if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):
. 我已经编写了以下代码,但失败并显示错误消息
TypeError: 'int' object has no attribute '__getitem__'
if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):
TypeError: 'int' object has no attribute '__getitem__'
在行中TypeError: 'int' object has no attribute '__getitem__'
if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):
The object json_string
is obtained with json_string = json.loads(text)
使用
json_string = json.loads(text)
获得对象json_string
def getField(dt,json_string):
fields = {k['type']: ((k['start-month'],k['start-day']),(k['end-month'],k['end-day'])) for k in json_string}
field = "NA"
for t, ranges in fields.items():
for start, end in ranges:
if date(dt.year,start[0],start[1]) <= dt.date() <= date(dt.year,end[0],end[1]):
field = t
break
if field != "NA":
break
return field
text = '''[{"end-day":31,"end-month":5,"type":"T1","start-day":10,"start-month":1},{"end-day":9,"end-month":1,"type":"T2","start-day":1,"start-month":9},{"end-day":30,"end-month":9,"type":"T3","start-day":1,"start-month":6}]'''
json_string = json.loads(text)
dt = datetime.strptime("2015-03-12 11:00:00.0", "%Y-%m-%d %H:%M:%S.%f")
getField(dt,json_string)
UPDATE: 更新:
The content of fields
: fields
内容:
{u'Type1': ((6, 1), (9, 30)),
u'Type2': ((1, 10), (5, 31)),
u'Type3': ((9, 1), (1, 9))}
From this: 由此:
if date(dt.year,start[0],start[1])
it is clear that you are expecting start
to be a tuple containing month and day. 很明显,您期望
start
是一个包含月和日的元组。 But if I do this: 但是,如果我这样做:
for t, ranges in fields.items():
for start, end in ranges:
print (f"start={start} end={end}")
I get: 我得到:
start=6 end=1
start=9 end=30
start=1 end=10
start=5 end=31
start=9 end=1
start=1 end=9
Now you can see where the error message is coming from. 现在,您可以查看错误消息的来源。
start[0]
means 6[0]
. start[0]
表示6[0]
。 Do this instead: 改为这样做:
for t, (start,end) in fields.items():
Then start
and end
will be the month/day tuples you expect. 然后
start
和end
将是您期望的月/日元组。
What you ought to be doing is 你应该做的是
start, end = ranges
rather than looping through them. 而不是遍历它们。 Also,
ranges
isn't a good name, something like date_pairs
might make more sense. 另外,
ranges
不是一个好名字,例如date_pairs
可能更有意义。
What you have in ranges
is a sequence of pairs (2 of them, to be exact). 您所拥有的
ranges
是一对序列(准确地说是2对)。 Thus the for
loop will iterate twice - once for the pair of ints representing the start date, and once for the pair of ints representing the end date. 因此,
for
循环将迭代两次-一次是代表开始日期的一对整数,一次是代表结束日期的一对整数。 In each iteration, start
and end
will be integers, not pairs, so you can't index them. 在每个迭代中,
start
和end
将是整数,而不是对,因此您无法为它们建立索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.