我得到一個TypeError,我不明白爲什麼。錯誤在c = t[i][0]
(根據調試器)。我有3個char組(列表):g1
,g2
和g3
我試圖通過從索引中減去密鑰的,k2
或k3
來更改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
過得好調用此? – ForceBru 2015-02-24 13:26:32
你可以顯示堆棧跟蹤嗎? – 2015-02-24 13:27:03
在哪一行產生類型錯誤?你能發佈整個消息嗎? – d6bels 2015-02-24 13:27:24