Python - 将字符串列表中的多个字符替换为基于字典的其他字符
Python - replace multiple chars in list of strings by other ones based on dictionary
我有一本任意字典例如:
a_dict = {'A': 'a', 'B':b, 'C': 'h',...}
和任意字符串列表,例如:
a_list = ['Abgg', 'C><DDh', 'AdBs1A']
我现在的目标是在python中找到一些简单的方法或算法,用相应的值替换字典中的关键元素。表示 'A' 被 'a' 替代,依此类推。所以结果将是列表:
a_result = ['abgg', 'h><DDh', 'adbs1a']
使用string.translate
和str.maketrans
import string
translate_dict = {'A': 'a', 'B':'b', 'C': 'h'}
trans = str.maketrans(translate_dict)
list_before = ['Abgg', 'C><DDh', 'AdBs1A']
list_after = [s.translate(trans) for s in list_before]
也许是这样的?
lut = {'A': 'a', 'B':'b', 'C': 'h'}
words = ["abh", "aabbhh"]
result = ["".join(lut.get(l, "") for l in lut) for word in words]
作为旁注,不要使用 python 中作为保留关键字的变量名,例如 list 或 dict。
我有一本任意字典例如:
a_dict = {'A': 'a', 'B':b, 'C': 'h',...}
和任意字符串列表,例如:
a_list = ['Abgg', 'C><DDh', 'AdBs1A']
我现在的目标是在python中找到一些简单的方法或算法,用相应的值替换字典中的关键元素。表示 'A' 被 'a' 替代,依此类推。所以结果将是列表:
a_result = ['abgg', 'h><DDh', 'adbs1a']
使用string.translate
和str.maketrans
import string
translate_dict = {'A': 'a', 'B':'b', 'C': 'h'}
trans = str.maketrans(translate_dict)
list_before = ['Abgg', 'C><DDh', 'AdBs1A']
list_after = [s.translate(trans) for s in list_before]
也许是这样的?
lut = {'A': 'a', 'B':'b', 'C': 'h'}
words = ["abh", "aabbhh"]
result = ["".join(lut.get(l, "") for l in lut) for word in words]
作为旁注,不要使用 python 中作为保留关键字的变量名,例如 list 或 dict。