Python 类型错误:';类型';对象不可为eval()下标
我在包含“if(eval(cond)):”的行中遇到“TypeError:“type”对象不可下标”错误。请解释我的错误所在。问题是您没有任何名为Python 类型错误:';类型';对象不可为eval()下标,python,typeerror,eval,Python,Typeerror,Eval,我在包含“if(eval(cond)):”的行中遇到“TypeError:“type”对象不可下标”错误。请解释我的错误所在。问题是您没有任何名为list的变量,因此Python假定您引用的是类型list(将“type”视为“数据类型”,如int,float,等等) 我相信您是想在cond字符串中使用I[j]而不是list[j]。如果是这种情况,用i[j]替换list[j],这样就可以了 def check(positions): final = [] n = len(positions
list
的变量,因此Python假定您引用的是类型list
(将“type”视为“数据类型”,如int
,float
,等等)
我相信您是想在cond
字符串中使用I[j]
而不是list[j]
。如果是这种情况,用i[j]
替换list[j]
,这样就可以了
def check(positions):
final = []
n = len(positions)
#positions is a list of lists. So now we'll break this into individual lists
#creating n empty lists
lists = [[] for _ in range(n)]
cond ="" #empty string to create condition
#fetching lists from list of lists
for k in range(n):
lists[k]=positions[k]
#computation work starts here
for i in lists[0]:
for j in range(1,n-1):
cond+= 'i+j in list[j] and '
cond+='i+n-1 in list[n-1]'
for i in lists[0]:
for j in range(1,n-1):
if(eval(cond)):
final.append(i)
return final
旁注:您不应该调用变量
list
,因为这可能与Python的list
数据类型冲突,并可能造成混乱。谢谢!!我弄错了。而不仅仅是“列表”,而我已经声明了“列表”。是的,最好避免使用类似于预定义数据类型的变量。@SameekshaGupta很高兴这有帮助!如果这回答了你的问题,请考虑把这个帖子作为一个答案。快乐编码!
for i in lists[0]:
for j in range(1,n-1):
cond+= 'i+j in i[j] and '
cond+='i+n-1 in i[n-1]'