0

How to convert a list [0,1,2,1] to a list of string, when we convert 0 to 'abc', 1 to 'f' and 2 to 'z'? So the output list will be ['abc','f','z','f'].

I did:

x = []
for i in xrange(input):
  if input[i] == ...
    x.append ('abc')
3

2 Answers 2

5

Use a dictionary as your translation table:

old_l = [0, 1, 2, 1]
trans = {0: 'abc', 1: 'f', 2: 'z'}

Then, to translate your list:

new_l = [trans[v] for v in old_l]
1

As an alternative to a dict, if you can guarantee that the numbers are sequential, you can just use a list and indexes:

subs = ['abc','f','z'] 
original = [0, 1, 2, 1]

result = [subs[x] for x in original]

Same idea as the dict, but marginally less to type?

Not the answer you're looking for? Browse other questions tagged or ask your own question.