【问题标题】:match and replace string items in list with string items from another list将列表中的字符串项匹配并替换为另一个列表中的字符串项
【发布时间】:2019-09-23 16:49:31
【问题描述】:

我有三个列表 - base, match, and replacmatchreplac 长度相同

base = ['abc', 'def', 'hjk']

match = ['abc', 'hjk']

replac = ['abcde', 'hjklm']

我想通过匹配match 中的字符串项来修改base 列表,并将它们替换为replac 中的相同索引项。

预期输出:base = ['abcde', 'def', 'hjklm']

【问题讨论】:

  • 我能想到的最好的方法是用match中的单词作为键,replac中的单词作为值,然后循环遍历base中的单词并替换它们。

标签: python list string-matching


【解决方案1】:

我会这样做:

mapp = dict(zip(match,replac))
res = [mapp[e] if e in mapp else e for e in base]

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2021-03-27
    • 2015-08-17
    • 2020-01-08
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多