5

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
1
  • Do you want to implement something like C enum in python? Commented Feb 9, 2013 at 23:00

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.