cvampal
cvampal

Reputation: 21

how to map the elements of a list to their values efficiently?

I have a list say list1 and I want to map its elements to corresponding values.

code = ['a','b','c']
value = [1,2,3]             
list1 = ['a','a','b','c','b','b','a','c']

here is the code that I wrote.

def codeToValue(code,value,list1):
    list1_out = [0 for i in range(len(list1))]
    for i in range(len(list1)):
        for j in range(len(code)):
            if list1[i] == code[j]:
                list1_out[i] = value[j]
    return list1_out

and I got output as desired.

print(codeToValue(code,value,list1))
[1, 1, 2, 3, 2, 2, 1, 3]

this code is fine for small size of lists but when I run it with large size of lists it's taking too much time because of two loops. Please suggest something so that it's time efficiency can be increased. Any suggestions will be greatly appreciated.

Upvotes: 2

Views: 76

Answers (1)

Delgan
Delgan

Reputation: 19627

You could use a dict (built thanks to zip()) and list comprehension:

mapping = dict(zip(code, value))
out = [mapping[v] for v in list1]

About efficiency: this snippet benefits from the O(1) dict-lookup (although you still need to iterate first trough the values of the dict), and as list comprehensions are known to be faster than plain for loops, you should expect better performance with this code.

If this is still too slow for your usage, you should probably use a specialized library in large data processing like pandas.

Upvotes: 5

Related Questions