python - 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”。
解决方案
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 - Django - 多对一关系不起作用
- python - 尝试在 PyGame 中从列表到屏幕绘制多个矩形图像时出现类型错误
- c# - 如何在 Blazor 的 Virtualize 组件中访问 ItemContent 中的项目索引
- python - 为什么这个 python 代码只在 main 中运行,而不在函数中运行?
- javascript - 我想知道在 express-session 中作为配置传递的密钥的漏洞
- python - 如何使用 python 使用 youtube data API v3 获取个性化搜索结果
- javascript - 如何在javascript中将月日值分配给div?
- python - 我在 QMainwindow 和 Qdialog 窗口之间切换,但是当我退出 QDIALOG 时,它会导致整个程序崩溃
- pytest - Pytest 显示随机顺序测试的顺序
- discord - 我将如何制作一个可以使用用户 ID 或名称#discriminator 的解禁命令