2013-06-27 215 views
1

我想让代码打破游戏,其中用户提交符号/字母对字典来破解代码,然后我希望代码使用字典来用配对的字母替换符号的每个实例。python使用字典替换字符串列表中的字符

我有下面的代码位:

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 

任何帮助,任何人都可以提供我将非常感激。

亚当

+0

对于许多不同的事情,你正在重复使用相同的变量名,避免这种情况。另外 - 你提到字典,但只使用列表。 –

回答

2

progression是一个列表。要访问它的内容,你需要使用索引值,这是一个整数,而不是一个字符串,因此是错误。

你可能想:

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

什么枚举所做的是通过文字的列表,其中i是索引值和j为内容的循环。 .get()dict['key']类似,但如果未找到密钥,则返回None而不是引发错误。

然后words[i]修改与字

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],而不是从clues钥匙更换progression[i]内容替换字符。

此外,将progression = words更改为progression = words[:]以便创建要采取行动的列表的副本。你传入一个单词的引用,然后将相同的引用分配给进程。当你操纵progression,所以你要操纵words,渲染progression无用的在这种情况下。

实施例使用:

print words 
print decrypter(words, clues) 
print words 

使用progression = words输出:

[ '超级', '随机', '列']
[ '超级', '秘密',“列表使用']
[' 超级”, '秘密', '列']

输出:

[ '超级', '随机', '列']
[ '超级', '秘密', '列']
[ '超级', '随机', '名单' ]