0

I have an array: array = ['wood', 'glass', 'metal', 'glass', 'glass', 'wood', 'metal', 'wood', 'glass', 'glass']

and I want to replace each string by a condition, for example: each 'wood' replace by 'blue', 'glass' by 'red' and 'metal' by 'green'.

so I get: ['blue', 'red', 'green', 'red', 'red', 'blue', 'green', 'blue', 'red', 'red']

I'm trying to do something like: ['red' if el == 'glass' for el in array]

I don't know how to do multiple conditions or even if this method is the right thing to do?

please help :)

2 Answers 2

2

You can use a dictionary to map old value to new values.

Example:

>>> name_mapping = {'wood':'blue'}
>>> res = [name_mapping.get(el, el) for el in array]
>>> res
['blue', 'glass', 'metal', 'glass', 'glass', 'blue', 'metal', 'blue', 'glass', 'glass']

dict.get with keep the current element in the result in case the element is not a key of the mapping dictionary.

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

Comments

1

Maybe create a dictionary:

dct = {'wood': 'blue', 'glass': 'red', 'metal': 'green'}
new_array = [dct[item] for item in array] 

2 Comments

This won't work when item is not one of the keys.
@cicolus yes obviously. this was just a quick demonstration how to use dictionaries with a list comprehension

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.