2015-02-24 109 views
0

我得到一個TypeError,我不明白爲什麼。錯誤在c = t[i][0](根據調試器)。我有3個char組(列表):g1,g2g3我試圖通過從索引中減去密鑰的​​,k2k3來更改char的索引。我現在使用的測試:Python:TypeError:'int'object is not subcriptable

text = 'abcd' 

l_text = [('a', 0), ('b', 1), ('c', 2), ('d', 3)] 

k1, k2, k3 = 2, 3, 1 

這是代碼:

def rotate_left(text, l_text, k1, k2, k3): 
    i = 0 
    newstr = [None]*len(text) 
    for t in l_text: # t = tuple 
     c = t[i][0] 
     if c in g1: # c = char 
      l = int(l_text[i][1]) # l = index of the char in the list 
      if l - k1 < 0: 
       newstr[l%len(text)-k1] = l_text[i][0] 
      else: 
       newstr[l-k1] = l_text[i][0] 
     elif c in g2: 
      l = l_text[i][1] # l = index of the char in the list 
      if l - k1 < 0: 
       newstr[l%len(text)-k2] = l_text[i][0] 
      else: 
       newstr[l-k2] = l_text[i][0] 
     else: 
      l = l_text[i][1] # l = index of the char in the list 
      if l - k1 < 0: 
       newstr[l%len(text)-k3] = l_text[i][0] 
      else: 
       newstr[l-k3] = l_text[i][0] 
     i += 1 
    return newstr 

有人能解釋我爲什麼我得到這個錯誤,我該如何解決?這不像我在那裏使用int類型。調試器顯示它是一個str類型,並在第二次迭代後中斷。

PS谷歌沒有幫助 PPS我知道代碼中有太多重複。我做到了在調試器中看到發生了什麼。

UPDATE:

Traceback (most recent call last): 
    File "/hometriplerotatie.py", line 56, in <module> 
    print(codeer('abcd', 2, 3, 1)) 
    File "/home/triplerotatie.py", line 47, in codeer 
    text = rotate_left(text, l_text, k1, k2, k3) 
    File "/home/triplerotatie.py", line 9, in rotate_left 
    c = t[i][0] 
TypeError: 'int' object is not subscriptable 
+0

過得好調用此? – ForceBru 2015-02-24 13:26:32

+1

你可以顯示堆棧跟蹤嗎? – 2015-02-24 13:27:03

+0

在哪一行產生類型錯誤?你能發佈整個消息嗎? – d6bels 2015-02-24 13:27:24

回答

3

您索引到每個個人元組:

c = t[i][0] 

i開始爲0,但你增加它每次循環迭代:

i += 1 

for循環結合t每個從l_text個人元組,所以首先t必然('a', 0),然後到('b', 1)

所以首先你要看('a', 0)[0][0]這是'a'[0]這就是'a'。下一個迭代你看('b', 1)[1][0]這是1[0]這會引發你的異常,因爲整數不是序列。您需要刪除i;你做不是需要在這裏保持一個運行索引,因爲for t in l_text:已經給你每個單獨的元組

+0

因爲沒有看到這個,我感到非常愚蠢。 Thx尋求幫助。 – Sensei 2015-02-24 13:38:49

+1

@Fizunik:調試器都很好,但是有策略地放置打印語句可以方便地追蹤這樣的東西。 – 2015-02-24 13:42:00

2

的錯誤是在這裏:

l_text = [('a', 0), ('b', 1), ('c', 2), ('d', 3)] 

... 

for t in l_text: # t = tuple 
    # t is a tuple of 2 items: ('a', 0) 
    c = t[i][0] # Breaks when i == 1 

我想你想:

c = t[0] 

它不會破壞第一次輪循環,因爲當i == 0,t[i]'a'然後t[i][0]也是'a'

1

您正在做索引部分錯誤。你的元組是1維的,所以你不能使用2維數組下標符號。 假設

t = ('a',0) 

你應該使用t[0]t[1]分別訪問a0

希望它能幫助.. :)

1

的問題是,t是一個元組,您訪問的元組,像一個列表中的元素。目前,您訪問的元素就像一個2D列表,因爲您的列表會導致嘗試索引字符。

for t in l_text: # t = tuple 
    c = t[i][0] 

應改爲

for t in l_text: # t = tuple 
    c = t[0]