itV*_*ico 3 python tuples list typeerror
我收到TypeError,但我不明白为什么。错误发生于c = t[i][0]
(根据调试器)。我有3个字符组(名单)g1
,g2
和g3
我试图通过减去关键的改变字符的索引k1
,k2
或者k3
从索引。我现在用于测试的内容:
text = 'abcd'
l_text = [('a', 0), ('b', 1), ('c', 2), ('d', 3)]
k1, k2, k3 = 2, 3, 1
Run Code Online (Sandbox Code Playgroud)
这是代码:
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
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下我为什么会出现此错误以及如何解决该错误吗?这不像我在int
那里使用的类型。调试器显示它是一个str类型,并且在第二次迭代后中断。
PS谷歌没有帮助PPS我知道代码中有太多重复。我这样做是为了查看调试器中正在发生的事情。
更新:
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
Run Code Online (Sandbox Code Playgroud)
您正在索引每个单独的元组:
c = t[i][0]
Run Code Online (Sandbox Code Playgroud)
i
开始于0
,但您在每次循环迭代时都将其递增:
i += 1
Run Code Online (Sandbox Code Playgroud)
该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:
已经给你每个单独的元组。