Python:TypeError: 'int' 对象不可订阅

标签 python list tuples typeerror

我得到一个 TypeError,我不明白为什么。错误在 c = t[i][0] (根据调试器)。我有 3 个字符组(列表):g1 , g2g3我试图通过减去键的 k1 来更改 char 的索引, k2k3从指数。我现在正在使用什么进行测试:

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 类型,它在第 2 次迭代后中断。

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

最佳答案

您正在为每个个人元组编制索引:

c = t[i][0] 

i0 开始,但您在每次循环迭代时递增它:

i += 1

for 循环将 t 绑定(bind)到 l_text 中的每个元组,因此首先 t 绑定(bind)到('a', 0),然后到('b', 1),等等

所以首先你要看的是 ('a', 0)[0][0] 这是 'a'[0] 这是 '一个'。您查看 ('b', 1)[1][0] 的下一次迭代是 1[0],它会引发您的异常,因为整数不是序列。

您需要删除i;您不需要在这里保留运行索引,因为 for t in l_text: 已经为您提供了每个单独的元组

关于Python:TypeError: 'int' 对象不可订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696982/

相关文章:

python - 使用 Python 查找顶级 Twitter 好友

python - 通过避免 NaN 滚动系列

c# - 为什么接口(interface)类型的列表不能接受继承接口(interface)的实例?

Python 2.7 - IPython 'raw_input' 并附加到列表 - 在每个项目之前添加 'u'

c# - 在 List<T> 中添加 List<DateTime> 值

python - 简单的 Twisted 服务器不会使用计时器写入

python - 为什么我在使用 IMDbPY 时会收到这么多警告和一些错误?

python - 根据元素有条件地连接python列表中元组的字符串值

Java N-Tuple 实现

c++ - for 循环期间的动态分配会造成内存泄漏吗?