Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

list - Using a dict to translate numbers to letters in python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...