user5170375
user5170375

Reputation:

Python: Replace occurrences of items in multiple lists?

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

Answers (3)

Sebastian Wozny
Sebastian Wozny

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

TayTay
TayTay

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

sam
sam

Reputation: 2033

Try this:

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

Output:

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

Demo

Upvotes: 2

Related Questions