Skip to main content
 首页 » 编程设计

Python:替换多个列表中出现的项目

2025年05月04日11Renyi-Fan

我有一些 list :

#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'] 

替换后,列表a必须是

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

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

而list a中list c的所有内容必须替换为csharp

可以重复。

请您参考如下方法:

试试这个:

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

输出:

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

Demo