python使用字典替换字符串列表中的字符

python使用字典替换字符串列表中的字符,python,dictionary,replace,Python,Dictionary,Replace,我正在尝试制作一个破译代码的游戏,用户将符号/字母对提交到字典以破译代码,然后我希望代码使用字典将符号的每个实例替换为成对的字母 我有以下代码: 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

我正在尝试制作一个破译代码的游戏,用户将符号/字母对提交到字典以破译代码,然后我希望代码使用字典将符号的每个实例替换为成对的字母

我有以下代码:

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:列表索引必须是整数,而不是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
任何人能提供的任何帮助我都将非常感激


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

您可能想要:

for i, j in enumerate(words):
    words[i] = clues.get(j)
enumerate所做的是遍历单词列表,其中
i
是索引值,
j
是内容
.get()
类似于
dict['key']
,但如果找不到该键,它将返回
None
,而不是引发错误

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

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

首先,正如前面指出的,您的命名约定很糟糕。它使代码更难阅读、调试和维护。选择简明的描述性名称,并确保遵循。避免为不同的事情重复使用相同的变量名,尤其是在同一范围内

现在,请看代码:

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]

另外,将
progression=words
更改为
progression=words[:]
,以便创建要执行操作的列表副本。您传入对单词的引用,然后将该引用指定给progression。当你操作
progression
时,你操作
words
,使得
progression
在这种情况下无法使用

示例使用:

print words
print decrypter(words, clues)
print words
使用
progression=words输出:

[‘超级’、‘随机’、‘列表’]
['Super'、'Secret'、'List']
['Super'、'Secret'、'List']

使用
progression=words[:]输出

[‘超级’、‘随机’、‘列表’]
['Super'、'Secret'、'List']
[‘超级’、‘随机’、‘列表’]


在许多不同的事情上使用相同的变量名,请避免这种情况。此外,您提到字典,但只使用列表。