【问题标题】:Python: Replace matches in list of strings according to replacement dict / replacement mapPython:根据替换字典/替换映射替换字符串列表中的匹配项
【发布时间】:2017-06-03 00:01:42
【问题描述】:

什么是最好的归档方式:

original_list = ["word_1", "word_2", "word"]
replacements = {
  'word_1': 'something',
  'word': 'number'
}
updated_list = replace_in_list(original_list, replacements)

在哪里

updated_list == ["something", "word_2", "number"]

【问题讨论】:

标签: python list dictionary replace


【解决方案1】:

单线:

>>> [replacements[w] if w in replacements else w for word in original_list]
['something', 'word_2', 'number']

【讨论】:

  • 这就是我会做的
  • 在列表推导中使用条件表达式是相当 Pythonic 的!
【解决方案2】:

使用列表理解来访问替换 dict 键,如果没有找到默认值作为原始字符串(使用get):

updated_list = [replacements.get(x,x) for x in original_list]

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 2021-09-18
    • 2016-09-26
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2014-03-12
    • 2021-09-23
    相关资源
    最近更新 更多