0

I have a list of numbers and list of strings:

data = [1, 2, 3, 1, 3]
labels = ['a','b','c']

How do I replace the numbers in data with the labels so that I will get data equals:

['a','b','c','a','c']

I tried setting labels to

mappings [('a', 1), ('b',2), ('c',3)]

and using a for loop to replace the data variable but I cannot seem to replace a list.

2

2 Answers 2

1

simple list comprehension with offset correction (in that case you don't need a dictionary)

data = [1, 2, 3, 1, 3]
labels = ['a','b','c']    

>>> [labels[i-1] for i in data]
['a', 'b', 'c', 'a', 'c']

with a dictionary:

mappings = {1: 'a', 2: 'b', 3: 'c'}
>>> [mappings[i] for i in data]
['a', 'b', 'c', 'a', 'c']
Sign up to request clarification or add additional context in comments.

Comments

0

You can use numpy for this:

import numpy as np
import itertools
np.array(labels)[[a - b for a,b in zip(data, itertools.cycle([1]))]].tolist() 

#  ['a', 'b', 'c', 'a', 'c']

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.