首页 > 解决方案 > Python - 用值替换每个等于字典键的列表字符

问题描述

我必须用相应的键值替换列表中的每个字母字符。例如,'hello' 中的 'h' 需要更改为 'u',这是字典键 'h' 的字典值:

我的代码:

list = ["hello", "1234kuku"]
dict = {'a': 'n', 'e': 'r','h': 'u', 'l': 'y', 'o': 'b', 'u': 'h','k': 'x'}

def encode(list, dict):
for word in list:
    for key, value in dict.items():       
        for char in word:
            if char == key:                        
                list = [w.replace(char, value) for w in list]
return(list)

print(encode(list,dict))

我的问题是我能够得到这个:

['hryyb', '1234xhxh']

但我需要这个:

['uryyb', '1234xhxh']

我知道这个问题与循环有关,因为它基本上将“hello”更改为“uryyb”,但在循环到第二个列表项并更改“1234kuku”后,它会将“uryyb”更改为“hryyb”。

标签: pythonlistdictionaryreplace

解决方案


Python 有这样的东西,maketrans. 例子:

# `list` and `dict` shadow built-in primitive types. Use different names
strings = ["hello", "1234kuku"]
d = {'a': 'n', 'e': 'r','h': 'u', 'l': 'y', 'o': 'b', 'u': 'h','k': 'x'}

tr = str.maketrans(d)
result = [s.translate(tr) for s in strings]

推荐阅读