Python\uuu getitem\uuu错误
我有一个简短的问题,这行代码Python\uuu getitem\uuu错误,python,Python,我有一个简短的问题,这行代码 row[time] == numbers[num_time]: 给了我一个错误: int has no attribute __getitem__ 经过一些研究,我发现在尝试调用int上的列表号时会出现这种错误。在本例中,我发送了一个包含3个数字的列表,并希望递归(我们还不允许使用循环:()在第二个数字列表中,查看第二个列表中的任何元素是否在第一个列表中。如果在第一个列表中,则会执行某些操作,但如果不在第一个列表中,则函数应移动到行列表中的下一个,执行相同的操作
row[time] == numbers[num_time]:
给了我一个错误:
int has no attribute __getitem__
经过一些研究,我发现在尝试调用int上的列表号时会出现这种错误。在本例中,我发送了一个包含3个数字的列表,并希望递归(我们还不允许使用循环:()在第二个数字列表中,查看第二个列表中的任何元素是否在第一个列表中。如果在第一个列表中,则会执行某些操作,但如果不在第一个列表中,则函数应移动到行列表中的下一个,执行相同的操作,直到行为空
def row_find(row,numbers,time,num_time):
if numbers==[]:
return row_find(row[time+1],numbers,time+1,num_time=0)
if row== []:
return row
else:
if row[time]== numbers[num_time]:
num_time=0
return row,row_find(row[time+1],numbers,time+1,num_time)
else:
return row,row_find(row[time],numbers[num_time+1],time,num_time)
lst=[5,2,9]
num_lst=[5, 10, 23, 31, 44]
row_find(lst,num_lst,0,0)
在这里:
您使用的是不是列表的数字[num\u time+1]
我认为这应该是一个诀窍:
def row_find(row,numbers,time,num_time):
if numbers==[]: # If numbers list is empty, it make no sense to contiue
return False
if row== []: # If numbers list is empty, it make no sense to contiue
return False
if row[time]== numbers[num_time]: #Already found an element that is in both lists
print("found -> " + str(time) + " " + str(num_time))
return True
else:
if num_time < len(numbers)-1: # If remaining elements in numbers
if row_find(row,numbers,time,num_time+1): # Check next one
return True
else: # I
if time < len(row)-1: # If remaining element in row
return row_find(row,numbers,time+1,0) # check numbers from beginning with next row
else:
return False # If not, no elements in both lists
lst=[8,2,9]
num_lst=[9, 10, 88, 31, 55]
row_find(lst,num_lst,0,0)
# found -> 2 0
def row_find(行、数字、时间、数字时间):
如果数字==[]:#如果数字列表为空,则继续没有意义
返回错误
如果行==[]:#如果数字列表为空,则继续没有意义
返回错误
如果行[time]==数字[num_time]:#已在两个列表中找到一个元素
打印(“找到->”+str(时间)+“+str(num_时间))
返回真值
其他:
如果num_time2 0
此处:
row_find(row[time],numbers[num_time+1],time,num_time)
return row,row_find(row[time],numbers[num_time+1],time,num_time)
您传递一个整数作为行的数值参数。您必须传递一个列表。您在寻找吗?您想做什么
row_find(row[time],numbers[1:],time,num_time)
其中[1:]返回从第二个元素开始的列表
您还可以使用Python布尔求值。如果序列为空,则将求值为False,而不是
if numbers==[]:
你可以做:
if not numbers:
检查您作为numbers
发送的内容可能是您发送的内容不是列表。您得到的错误是Pythons告诉您,您要求在错误的对象上使用函数,attribute\uuu getitem\uuuuu
正在到达列表的索引numbers
,就像这样numbers[1]
您需要做几件事:
首先,检查您的参数(数字)是否实际上是一个列表。将其添加到函数顶部:
if not isinstance(numbers, collections.Iterable):
# error! numbers is meant to be a list. report on this error somehow
在代码的后面部分:
对于num\u lst=[5,10,23,31,44]
,num\u lst[0]=5
,num\u list[0++]=10
。如果“numbers”是10,那么numbers[num\u time]
意味着什么?(即,10[num\u time]
-这应该是什么意思?)
不要将数字[num_time+1]
作为参数传回函数,而要考虑使用切片。这不应该转化为数字[1]?我只需要它继续下一个数字,我需要把它放在if中吗?或者将它更改为num_time+=1?我用工作代码更新了我的答案,检查这是否是您需要的有时,row_find
返回一个元组,有时返回一个列表(row
)。您确定要这样做吗?