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
  • How about use dict as a map? For example, map=dict(0='abc'), then map['0'] = 'abc'. Commented Sep 14, 2017 at 15:04
  • Possible duplicate of Is a Python dictionary an example of a hash table? Commented Sep 14, 2017 at 15:06
  • OP, did either of the proposed answers answer your question? Commented Sep 20, 2017 at 15:12

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

Comments

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?

Comments

Your Answer

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.