简体   繁体   English

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

[英]python using a dictionary to replace characters in a list of strings

I am trying to make a code breaking game where the user submits symbol/letter pairs to a dictionary to crack a code, I then want the code to use the dictionary to replace each instance of a symbol with the paired letter. 我正在尝试制作一个代码破解游戏,用户将字符/字母对提交到字典以破解代码,然后我希望代码使用字典用配对字母替换符号的每个实例。

I have the following bits of code: 我有以下几点代码:

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

I have tried the following but it failed with: TypeError: list indices must be integers, not str 我尝试了以下但它失败了: 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

Any help that anyone could offer I would be very grateful. 任何人都可以提供任何帮助我将非常感激。

Adam 亚当

progression is a list. progression是一个清单。 To access content from it, you need to use the index value, which is an integer, and not a string, hence the error. 要从中访问内容,您需要使用索引值,它是一个整数,而不是字符串,因此是错误。

You probably want: 你可能想要:

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

What enumerate does is loops through the list of words, where i is the index value and j is the content. 枚举的作用是遍历单词列表,其中i是索引值, j是内容。 .get() is similar to dict['key'] , but if the key is not found it returns None instead of raising an error. .get()类似于dict['key'] ,但如果未找到该键,则返回None而不是引发错误。

Then words[i] modifies the list with the index number of the word 然后, words[i]使用单词的索引号修改列表

Haidro explained it pretty well, but I thought I'd expand his code, and also address another issue. 海德罗解释得很好,但我想我会扩展他的代码,并解决另一个问题。

First off, as Inbar Rose pointed out, your naming conventions bad. 首先,正如Inbar Rose指出的那样,你的命名惯例很糟糕。 It makes code much more difficult to read, debug, and maintain. 它使代码更难以阅读,调试和维护。 Pick concise descriptive names, and make sure to follow PEP-8 . 选择简洁的描述性名称,并确保遵循PEP-8 Avoid re-using the same variable name for different things, especially within the same scope. 避免为不同的事物重复使用相同的变量名,尤其是在同一范围内。

Now, to the code: 现在,代码:

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

This now replaces characters in the content of progression[i] instead of replacing progression[i] with the key from clues . 这现在取代了progression[i]内容中的字符,而不是用clues的密钥替换progression[i]

Also, changed progression = words to progression = words[:] in order to create a copy of the list to act on. 此外,更改了progression = words to progression = words[:] ,以便创建要执行的列表的副本。 You pass in a reference to words, and then assign that same reference to progression. 您传入对单词的引用,然后将相同的引用分配给进度。 As you manipulate progression , so to do you manipulate words , rendering progression useless to be using in this case. 当你操纵progression ,你要操纵words ,在这种情况下渲染progression无用。

Example using: 示例使用:

print words
print decrypter(words, clues)
print words

Output using progression = words : 输出使用progression = words

['Super', 'Random', 'List'] ['超级','随机','列表']
['Super', 'Secret', 'List'] ['超级','秘密','列表']
['Super', 'Secret', 'List'] ['超级','秘密','列表']

Output using progression = words[:] : 输出使用progression = words[:]

['Super', 'Random', 'List'] ['超级','随机','列表']
['Super', 'Secret', 'List'] ['超级','秘密','列表']
['Super', 'Random', 'List'] ['超级','随机','列表']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM