Python:TypeError:'int'对象是unsubscriptable

时间:2012-10-03 19:27:28

标签: python

我编写了一个程序来计算Weyl组的根。但是,我收到以下错误。

Traceback (most recent call last):
  File "./rootsAn.py", line 58, in <module>
    equals = isequal(x[0],y[0])
TypeError: 'int' object is unsubscriptable

我查了一下这个错误,但据我所知,x[0]y[0]都是数组,而不是ints。我的代码是:

def innerprod(a,b):
    x = 0
    y = 0
    while x < len(a):
        y += a[x]*b[x]
        x += 1
    return y

def isequal (a,b):
    x = len(a)- 1
    y = 0
    counter = 0
    while y < x:
        if a[y] == a[x]:
            counter+=1
        else:
            counter +=0
        y += 1
    if counter == x:
        return True
    else:
        return False


simplerootsht = []
simpleroots = []
positiverootsht=[]
positiveroots = []
dim = 3

n = 0
while n < dim-1:
        x = []
        s = 0
        while s < dim:
            if s == n:
                x.append(1)
            elif s == n + 1:
                x.append(-1)
            else:
                x.append(0)
            s += 1
        simplerootsht.append([x,1])
        simpleroots.append(x)
        n += 1
for c in simpleroots:
    positiveroots.append(c)
for d in simplerootsht:
    positiverootsht.append(d)

print positiverootsht

for x in positiverootsht:
    for y in simplerootsht:
        equals = isequal(x[0],y[0])
        if equals == True:
            pass
        print x[0], y[0]
        b = innerprod(x[0], y[0])
        a = len(x[0])
        if b == 0:
            pass
        else:
            r = x[1]
            q = r - b
            print r, q
            x = 1
            while x < q: 
                z = [sum(pair) for pair in zip(x[0], x*y[0])]
                if z not in positiveroots:
                    positiveroots.append(z)
                    positiverootsht.append([z,x[1] + y[1]])
                x += 1

谢谢!

2 个答案:

答案 0 :(得分:3)

for x in positiverootsht:

positiverootsht是一个整数列表..当你迭代它们时,它们会在x中给出整数。所以,x实际上是一个int ..它们不能像{{1}中的x [0]那样下标方法..

isequal()也是如此..它也是y类型。

因此,以下行不起作用: -

int

相反,您可以更改循环中使用的变量以使其正常工作。那时equals = isequal(x[0],y[0]) 将仅作为您在方法中先前声明的列表。

答案 1 :(得分:1)

在您的示例中,x遍历positiverootsht的元素。 positiveroots会从simpleroots添加{int}。因此xy都是整数。

您正在重复使用这些变量,所以虽然x之前是一个数组,但您将其转换为带有这些行的int:

for x in positiverootsht:
    for y in simplerootsht: