Map values in a List based on custom Dictionary - Python

Pdeuxa

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.

9769953

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.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

Map list elements to keys in dictionary for decimal values in python

assign list values to dictionary python

Convert dictionary into list with length based on values

Creating new matrix based on dictionary values and a list

Python map dictionary values to XML file

python sorting list of dictionary by custom order

sorting python list based on "dependencies" from dictionary

Python: Create list of lists as dictionary values

compare list values withina python dictionary

How to assign values to a python dictionary inside a list

Remove multiple values from [list] dictionary python

Getting the correct list values in a python dictionary

Store dictionary with list values in csv using python

python3 dictionary, values as a list

python: Turn dictionary int values into list

Replacing values from list of custom objects with map values

Python - Return the dictionary key comparing dictionary values with list

How to replace group of strings in pandas series based on a dictionary with values as list?

Map dictionary values in Pandas

Sort C# Dictionary by a custom array/list, and output reordered dictionary Values as list

Create a new dictionary in python with unique values based in the second parameter

Python-Convert values in a list based on a range

Displaying List values in a Dictionary

Convert a list returned by a map() function (from the Pool class) to a Dictionary in Python

replace dictionary values with list of values

using lambda, filter for extracting values from a dictionary based on list key values

In Python: Create a dictionary from a list of keys, but set all values to 0?

How to access the following list and dictionary values in Python3?

Python: create a nested dictionary from a list of parent child values

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo