Using a dict to translate numbers to letters in python

自古美人都是妖i 提交于 2021-02-13 17:37:34

问题


I have a string 'alphabet' with all the letters in the alphabet and a list of ints corresponding to those those letters (0-25).

Ex:

num_list = [5,3,1] would translate into letter_list = ['f','d','b']

I currently can translate with:

letter_list = [alphabet[a] for a in num_list]

However, I would like to use a dict for the same thing, retrieve 'letter' keys from dict with 'number' values.

alpha_dict = {'a':0,'b':1,'c':2}... etc

How do I change my statement to do this?


回答1:


Simply iterate through your alphabet string, and use a dictionary comprehension to create your dictionary

# Use a dictionary comprehension to create your dictionary
alpha_dict = {letter:idx for idx, letter in enumerate(alphabet)}

You can then retrieve the corresponding number to any letter using alpha_dict[letter], changing letter to be to whichever letter you want.

Then, if you want a list of letters corresponding to your num_list, you can do this:

[letter for letter, num in alpha_dict.items() if num in num_list]

which essentially says: for each key-value pair in my dictionary, put the key (i.e. the letter) in a list if the value (i.e. the number) is in num_list

This would return ['b', 'd', 'f'] for the num_list you provided




回答2:


You could also invert alpha_dict to do this:

>>> import string
>>> alpha_dict = dict(enumerate(string.ascii_lowercase))
>>> alpha_dict
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z'}
>>> numbers = [5, 3, 1]
>>> [alpha_dict[x] for x in numbers]
['f', 'd', 'b']

This way your dictionary maps numbers to letters, instead of letters to numbers.




回答3:


You can build a dict of letter/numbers as such:

import string

alpha_dict = {
    i: string.ascii_lowercase[i]
        for i in list(range(0, len(string.ascii_lowercase)))
}

num_list = [5,3,1]
letter_list = [alpha_dict.get(a) for a in num_list]

However it would be easier just to use the list like this:

import string

num_list = [5,3,1]
letter_list = [string.ascii_lowercase[a] for a in num_list]



回答4:


I think -- like the other answers -- that a list should be used (to utilize the handy index calling) but dictionaries should NOT be used, period. SO...

    from string import ascii_lowercase # ONLY import ascii_lowercase
    numList = [numbers, in, your, list] # like you said in your question
    translation = "".join ([ascii_lowercase[num] for num in numList])


来源:https://stackoverflow.com/questions/48915456/using-a-dict-to-translate-numbers-to-letters-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!