Reputation:
I have some lists:
#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']
After the replacements, the list a
must be
# list a after replacements
a = ['python', 'cplusplus', 'csharp', 'cplusplus', 'csharp', 'csharp', 'cplusplus']
I want to replace all the occurrences of items in list b
in list a
with cplusplus
,
while all the contents of list c
in list a
must be replaced with csharp
Repetations are acceptable.
Upvotes: 1
Views: 133
Reputation: 17506
For your particular problem this will work:
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)
Upvotes: 2
Reputation: 7160
sam2090's code was right, but will take two passes for each of b
and c
. A way to do it in one pass:
['cplusplus' if i in b else 'csharp' if i in c else i for i in a]
Upvotes: 1