Python-用值替换与字典键相等的每个列表字符

Python-用值替换与字典键相等的每个列表字符,python,list,dictionary,replace,Python,List,Dictionary,Replace,我必须用键的相应值替换列表中的每个字母字符。例如,“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, val

我必须用键的相应值替换列表中的每个字母字符。例如,“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”,但在循环到第二个列表项并将“1234ku”改为“hryyb”后,它将“uryyb”改为“hryyb”。

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]

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]

请改为尝试此一行:
result=[“”.join(dct.get(x,”)表示s中的x)表示lst中的s]
。它避免了失败带来的O(n3)或O(n4)复杂性program@Jean-FrançoisFabre稍微调整一下dct.get(x,x)数字应该是keptupdateindenting@Jean-Françoisfare发现oneliner将来自kuku的数字1234进行OMmitt,因此它输出xhxh而不是1234xhxh。谢谢你!啊,刚才看到@rioV8的评论,是的,dct.get(x,x)帮助保留了数字。非常感谢。请改为尝试此一行:
result=[“”.join(dct.get(x,”)表示s中的x)表示lst中的s]
。它避免了失败带来的O(n3)或O(n4)复杂性program@Jean-FrançoisFabre稍微调整一下dct.get(x,x)数字应该是keptupdateindenting@Jean-Françoisfare发现oneliner将来自kuku的数字1234进行OMmitt,因此它输出xhxh而不是1234xhxh。谢谢你!啊,刚才看到@rioV8的评论,是的,dct.get(x,x)帮助保留了数字。非常感谢。太神了今天我学会了。天哪!经过10个小时的反复思考,我所需要的就是MAKETRANS!我从来没有听说过,今天我也学到了!非常感谢你!成功了!太神了今天我学会了。天哪!经过10个小时的反复思考,我所需要的就是MAKETRANS!我从来没有听说过,今天我也学到了!非常感谢你!成功了!