在Python中使用字典将数字转换为字母

1 python dictionary list

我有一个字符串“alphabet”,其中包含字母表中的所有字母以及与这些字母相对应的整数列表(0-25)。

前任:

num_list = [5,3,1] would translate into letter_list = ['f','d','b']
Run Code Online (Sandbox Code Playgroud)

我目前可以翻译:

letter_list = [alphabet[a] for a in num_list]
Run Code Online (Sandbox Code Playgroud)

但是,我想使用字典来做同样的事情,从字典中检索带有“数字”值的“字母”键。

alpha_dict = {'a':0,'b':1,'c':2}... etc
Run Code Online (Sandbox Code Playgroud)

我如何更改我的声明才能做到这一点?

sac*_*cuL 5

只需迭代字符串alphabet,然后使用字典理解来创建字典

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

然后,您可以使用 检索任何字母对应的数字alpha_dict[letter],将 更改letter为您想要的任何字母。

然后,如果您想要与您的 对应的字母列表num_list,您可以这样做:

[letter for letter, num in alpha_dict.items() if num in num_list]
Run Code Online (Sandbox Code Playgroud)

这实质上是说:对于我的字典中的每个键值对,如果值(即数字)位于列表中,则将键(即字母)放入列表中num_list

这将返回['b', 'd', 'f']num_list提供的