1

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.

3 Answers 3

2

Try this:

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

Output:

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

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

And then to address his second point, ['csharp' if i in c else i for i in a]
@Tgsmith61591 Yeah. No need to repeat same code above :)
2

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)

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.