【问题标题】:Python - replace multiple chars in list of strings by other ones based on dictionaryPython - 根据字典将字符串列表中的多个字符替换为其他字符
【发布时间】:2022-01-06 19:50:59
【问题描述】:

我有一本任意字典,例如:

a_dict = {'A': 'a', 'B':b, 'C': 'h',...}

和任意字符串列表,例如:

a_list = ['Abgg', 'C><DDh', 'AdBs1A']

我现在的目标是在 python 中找到一些简单的方法或算法,将字典中的关键元素替换为相应的值。表示“A”被“a”代替,依此类推。所以结果将是列表:

a_result = ['abgg', 'h><DDh', 'adbs1a']

【问题讨论】:

    标签: python string list dictionary replace


    【解决方案1】:

    使用string.translatestr.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]
    

    【讨论】:

      【解决方案2】:

      也许是这样的?

      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。

      【讨论】: