TypeError:'type'对象不可用于eval()下标

问题描述 投票:-1回答:1
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

我在包含“ if(eval(cond)):”的行上收到“ TypeError:'type'对象不可下标”错误。请解释我要去哪里错了。

python typeerror eval
1个回答
1
投票

问题是您没有名为list的任何变量,因此Python假定您正在引用类型list(将“类型”视为“数据类型”,例如intfloat等) ..)。

我相信您打算在i[j]字符串中使用list[j]而不是cond。如果是这种情况,请用list[j]替换i[j],并且应该这样做。

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]'

附带说明:您不应调用变量list,因为它可能与Python的list数据类型冲突并可能造成混乱。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.