I have a list of numbers:
a = [4,4,4,4,4,4,4,4,4,........................,4,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4]
I want to transform the values according to a custom dictionary, for example:
cust_dict ={4:'four',1:'one',2:'two',3:'three'}
To get the following:
a= [four,four,four,four,four.....,four, three,two,....]
The only code I have done is with a for loop:
for i in range(len(a)):
a[i] = cust_dict[a[i]]
Is there a more efficient way (in pure python), thus avoiding for-loop ? For a list of 35k items I took around 4ms with this code.
With 35K items, I would use a NumPy array, or in this context, a Pandas Series (this obviously ignores the "pure Python" mention in your question):
>>> import pandas as pd
>>> a = [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 3]
>>> cust_dict ={4:'four',1:'one',2:'two',3:'three'}
>>> s = pd.Series(a)
>>> s.map(cust_dict).tolist()
['four', 'four', 'four', 'four', 'four', 'four', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'two', 'two', 'two', 'four', 'four', 'four', 'one', 'one', 'one', 'one', 'two', 'two', 'two', 'three']
But you may not want to convert the series back to a list, depending on further needs and usage.
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras