【问题标题】:Python: Replace occurrences of items in multiple lists?Python:替换多个列表中出现的项目?
【发布时间】:2016-01-13 05:07:55
【问题描述】:

我有一些清单:

#list a
a = ['python', 'c++', 'c#', 'c-plus-plus', 'c-sharp', 'csharp', 'cplus']

# list b 
b = ['c++', 'c-plus-plus', 'cplus', 'c-plusplus', 'cplusplus']

# list c
C = ['c#', 'c-sharp', 'csharp']

替换后,list a 必须是

# list a after replacements
a = ['python', 'cplusplus', 'csharp', 'cplusplus', 'csharp', 'csharp', 'cplusplus']

我想用cplusplus替换list alist b中出现的所有项目,

list alist c的所有内容都必须替换为csharp

可以重复。

【问题讨论】:

    标签: python list replace


    【解决方案1】:

    试试这个:

    ['cplusplus' if i in b else i for i in a]
    

    输出:

    ['python', 'cplusplus', 'c#', 'cplusplus', 'c-sharp', 'csharp', 'cplusplus']

    Demo

    【讨论】:

    • 然后解决他的第二点,['csharp' if i in c else i for i in a]
    • @Tgsmith61591 是的。无需重复上面相同的代码:)
    【解决方案2】:

    对于您的特定问题,这将起作用:

    def replace_synonyms(target,synonyms):
        """ Replaces all occurences of any word in list target with last element in synonyms """
        return [synonyms[-1] if word in synonyms else word for word in target]
    a=replace_synonyms(a,b)
    a=replace_synonyms(a,c)
    

    【讨论】:

      【解决方案3】:

      sam2090 的代码是正确的,但对于 bc 将分别进行两次传递。一种一次性完成的方法:

      ['cplusplus' if i in b else 'csharp' if i in c else i for i in a]
      

      【讨论】:

        猜你喜欢
        • 2012-11-11
        • 1970-01-01
        • 2014-08-22
        • 2022-12-06
        • 2011-12-15
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多