python - 为什么我的代码不根据字典解码加密字符串?

标签 python python-2.7 dictionary encryption replace

我有一个字典,其中包含代表字母的键和值。

例如一个简单的:

DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}

我收到了一个加密代码,并将该字符串变成了一个列表,其中每一项都是一个单词。我需要根据字典中的条目来解决它。

一个代码示例是:

words_list = ["bppx","xnt!"]  # "good day!"

我试图通过使用双循环来解决它,如下所示:

 for word in words_list:
     for char in word:
         if char in string.letters:
            word = word.replace(char, DICT_CODE.get(char))
 print words_list

预期输出 -> ["good","day!"]

输出 -> ["bppx","xnt!"]

它根本不起作用。字符保持不变,代码仍然未知。 我不明白为什么它不起作用,如果有人有时间查看并尝试帮助我看看哪里出了问题,或者甚至提出更好的方法(可行)。

最佳答案

更改 for 循环内的 word 变量,不会更改 word_list 内的字符串。您需要记住索引并更新该索引处的元素(并从索引中获取单词)-

for i, word in enumerate(words_list):
    for char in word:
            if char in string.letters:
                    words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))

演示 -

>>> words_list = ["bppx","xnt!"]
>>> DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}
>>> for i, word in enumerate(words_list):
...     for char in word:
...             if char in string.letters:
...                     words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
>>> words_list
['good', 'day!']

但对您来说更简单的方法是使用 str.translate (连同 string.maketrans )。示例 -

table = string.maketrans('bnpxt','gaody') #First argument characters in your original string, and second argument what they map to.
for i, word in enumerate(words_list):
    words_list[i] = word.translate(table)

演示 -

>>> import string
>>> table = string.maketrans('bnpxt','gaody')  #This creates the translation table
>>> words_list = ["bppx","xnt!"]
>>> for i, word in enumerate(words_list):
...     words_list[i] = word.translate(table)
... 
>>> print words_list
['good', 'day!']

这使用列表理解 -

words_list[:] = [word.translate(table) for word in words_list]

演示 -

>>> words_list = ["bppx","xnt!"]
>>> table = string.maketrans('bnpxt','gaody')
>>> words_list[:] = [word.translate(table) for word in words_list]
>>> words_list
['good', 'day!']

关于python - 为什么我的代码不根据字典解码加密字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807509/

相关文章:

在任意位置插入列的 Pythonic 方式

python - Mac OS X 上的 pygettext.py 和 msgfmt.py

python - 将较短长度的 Numpy 数组连接到 Pandas Dataframe

python-2.7 - 如何包含位于模块中但在 Sphinx 中的类和方法之外的文档字符串/注释

python-2.7 - Kivy 中 ScrollView 中的 TreeView - 无滚动

c# - 如何合并 Generic.Collection.List 和 Generic.Collection.Dictionary

python - 如何获取嵌套字典列表中所有键的路径

python - 包含字典的类属性

Python tkinter : Using a "textvariable" in a combobox seems useless

python 2.7 : len() returns wrong value for line from file with newline character