TypeError: list indices must be integers

TypeError: list indices must be integers

我正在尝试将一个列表中的项目插入到另一个列表中,并使用数字列表中的项目作为索引,但即使我使用整数作为索引编号,我仍收到此错误

另一件事是同一项目在错误之前的行中被接受为索引

我什至尝试在那里放一个数字来测试它,但它给了我同样的错误

代码如下:

FoundLetters = ['p', 'l', '-', 'i', 'n']
MissingLetters = []
AllLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
              'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def MissingCount():
    for j in range(len(FoundLetters)):
        if FoundLetters[j] == '-':
            MissingLetters.append(int(j))


def iterate():
    for i in range(len(AllLetters)):
        for i in AllLetters:
            FoundLetters.pop(MissingLetters[0])
            FoundLetters.insert(MissingLetters[0], AllLetters[i])


MissingCount()
iterate()

准确的错误是:

Traceback (most recent call last):
File "main.py", line 26, in <module>
iterate()
File "main.py", line 22, in iterate
FoundLetters.insert(MissingLetters[0], AllLetters[i])
TypeError: list indices must be integers or slices, not str


** Process exited - Return Code: 1 **
Press Enter to exit terminal

您的代码存在的问题是您在迭代函数中使用了两次 i。所以你正在覆盖第一个 i.因此,您正在遍历 AlLLetters 并尝试使用像“a”这样的字符串为 AllLeters 编制索引。尝试改变第二个循环

我建议使用 itertools.product 生成所有可能的替换组合:

import itertools
import string

found_letters = "pl-in"
missing_indices = [i for i, c in enumerate(found_letters) if c == "-"]

possible_words = (''.join(
    r[i] if i in r else c
    for i, c in enumerate(found_letters)
) for r in (
    dict(zip(missing_indices, p))
    for p in itertools.product(
        string.ascii_lowercase,
        repeat=len(missing_indices)
    )
))

print(list(possible_words))  # ['plain', 'plbin', ...]

repeat 与缺失字母的数量一起使用,无论缺失字母的数量如何,它都可以正常工作。在上面的代码中,p 是一个产品('a''b'、...),r 是给定产品的替换图({2: 'a'} , {2: 'b'}, ...)。当 found_letters 中有多个 - 时,每个 p 将有那么多字母('aa''ab'、...)和 r 会将每个 - 的位置映射到应该替换它的字母({2: 'a', 4: 'a'}{2: 'a', 4: 'b'}、...)。

请注意,如果缺少很多字母,possible_words 的序列将很快变得非常大,因为它是指数级的!虽然当你想要打印整个东西时将它变成 list 很方便,但你可能希望将它保留为生成器形式,这样你就可以通过英语词典过滤它,并在看到它们时删除所有无意义的单词.