2012-10-03 19 views
0

我寫了一個程序來計算Weyl組的根。但是,我收到以下錯誤。Python:TypeError:'int'object is unsubscriptable

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 

謝謝!

+3

'如果條件:返回True,否則:返回返回FALSE。嗯 – NullUserException

+4

這真的很難讀,因爲你重複使用變量'x'是幾種完全不同的方法..我建議試圖更具描述性,並使用更多的功能(所以更容易追蹤變量來自哪裏)。 –

回答

1

在您的示例中,x重複遍歷positiverootsht的元素。 positiveroots被添加到從simpleroots其中有ints。所以xy都是整數。

正在重用的變量,因此,雖然x是一個數組越早把它變成一個int與這些行:

for x in positiverootsht: 
    for y in simplerootsht: 
+0

謝謝,我剛剛意識到所有我稱之爲相同的地方。將名稱更改爲更具描述性的內容會照顧到錯誤! – Mary

3
for x in positiverootsht: 

positiverootsht是整數列表..他們會給整數X,當你遍歷他們。所以,x是實際上是一個int..They不能下標,比如x [0] isequal()方法..

所以是y ..它也是一個int類型。

所以,下面一行將無法正常工作: -

equals = isequal(x[0],y[0]) 

而是你可以改變你在循環使用的變量得到它的工作。至於那麼x會名單隻喜歡你的行爲在您的方法中早先聲明..

+0

其實在犯罪行之前,他在for循環中使用x和y – ajon

+0

@ajon ..沒有注意到.. ..更新了我的答案.. –

+0

Downvoter可以刪除投票..因爲我更新了我的帖子.. –

相關問題