Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...