Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning integers to strings

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!

like image 300
hayleyelisa Avatar asked Feb 09 '13 22:02

hayleyelisa


Video Answer


1 Answers

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.

like image 132
Volatility Avatar answered Oct 13 '22 23:10

Volatility