使用字典将数字转换为python中的字母 [英] Using a dict to translate numbers to letters in python
问题描述
我有一个字符串'alphabet',其中包含字母表中的所有字母,以及与这些字母相对应的整数列表(0-25).
I have a string 'alphabet' with all the letters in the alphabet and a list of ints corresponding to those those letters (0-25).
例如:
num_list = [5,3,1] would translate into letter_list = ['f','d','b']
我目前可以翻译:
letter_list = [alphabet[a] for a in num_list]
但是,我想将dict用于同一件事,从具有'number'值的dict中检索'letter'键.
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?
推荐答案
只需遍历您的 alphabet
字符串,并使用字典理解功能来创建字典
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)}
然后,您可以使用 alpha_dict [letter]
将任何字母替换为对应的数字,将 letter
更改为所需的任何字母.
You can then retrieve the corresponding number to any letter using alpha_dict[letter]
, changing letter
to be to whichever letter you want.
然后,如果您想要与 num_list
相对应的字母列表,则可以执行以下操作:
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]
基本上是这样说的:对于字典中的每个键值对,如果值(即数字)在 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
这将为您提供的 num_list
返回 ['b','d','f']
这篇关于使用字典将数字转换为python中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!