1

我正在尝试制作一个密码破解游戏,其中用户将符号/字母对提交给字典以破解代码,然后我希望代码使用字典用配对字母替换符号的每个实例。

我有以下代码:

words = imported list of coded words where each letter is replaced by a symbol. from a text file so i can change later
clues = dictionary of symbol and letter pairs that can be added to, removed from

我尝试了以下方法,但失败了:TypeError: list indices must be integers, not str

def converter(words,clues):

    progression = words


    for words in progression:#cycles through each coded word in the list
        for key in clues: #for each symbol in the dictionary
            progression[words] = progression[words].replace(key, clues[key]) #replaces


    return progression

任何人都可以提供的任何帮助,我将不胜感激。

亚当

4

2 回答 2

2

progression是一个列表。要从中访问内容,您需要使用索引值,它是一个整数,而不是字符串,因此会出现错误。

你可能想要:

for i, j in enumerate(words):
    words[i] = clues.get(j)

enumerate 所做的是遍历单词列表,其中i是索引值,j是内容。.get()类似于dict['key'],但如果未找到密钥,则返回None而不是引发错误。

然后words[i]用单词的索引号修改列表

于 2013-06-27T14:41:43.837 回答
1

Haidro解释得很好,但我想我会扩展他的代码,并解决另一个问题。

首先,正如Inbar Rose指出的那样,您的命名约定不好。它使代码更难阅读、调试和维护。选择简洁的描述性名称,并确保遵循PEP-8。避免为不同的事物重复使用相同的变量名,尤其是在相同的范围内。

现在,到代码:

words = ['Super', 'Random', 'List']
clues = {'R': 'S', 'd': 'r', 'a': 'e', 'o': 'e', 'm': 't', 'n': 'c'}


def decrypter(words, clues):

    progression = words[:]

    for i, word in enumerate(progression):
        for key in clues:
            progression[i] = progression[i].replace(key, clues.get(key))

    return progression

这现在替换内容中的字符,progression[i]而不是替换progression[i]为来自的键clues

此外,更改progression = wordsprogression = words[:]以创建要操作的列表的副本。您传入对单词的引用,然后将相同的引用分配给进程。当您操作progression时,您也操作wordsprogression在这种情况下使用变得无用。

使用示例:

print words
print decrypter(words, clues)
print words

输出使用progression = words

['Super', 'Random', 'List']
['Super', 'Secret', 'List']
['Super', 'Secret', 'List']

输出使用progression = words[:]

['Super', 'Random', 'List']
['Super', 'Secret', 'List']
['Super', 'Random', 'List']

于 2013-06-27T16:46:08.410 回答