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!
Rushy Panchal
17.7k16 gold badges66 silver badges94 bronze badges
asked Feb 9, 2013 at 22:54
hayleyelisa
3594 gold badges5 silver badges15 bronze badges
-
Do you want to implement something like C enum in python?begemotv2718– begemotv27182013年02月09日 23:00:22 +00:00Commented Feb 9, 2013 at 23:00
1 Answer 1
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.
answered Feb 9, 2013 at 22:56
Volatility
32.4k11 gold badges85 silver badges90 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py