I'm working in Python and I have a list of integers: [1, 2, 1, 3, 2, 2, 1, 3]
.
I want to assign each integer a string as if it were a variable:
['red', 'orange', 'red', 'yellow', 'orange', 'orange', 'red', 'yellow']
.
How would I go about doing this?
In that example, 1
corresponds to 'red'
, 2
corresponds to 'orange'
, and 3
corresponds to 'yellow'
.
Thanks!
Use a dictionary.
d = {1: 'red', 2: 'orange', 3: 'yellow'}
Then you can do this to change the list:
lst = [d[k] for k in lst]
The dictionary basically 'maps' objects (in this case integers) to other objects, which is just what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With