[英]List of letters, into a list of numbers
I'm trying to find a simple way of converting a list of letters, into a list of numbers.我试图找到一种将字母列表转换为数字列表的简单方法。 Given each letter has a certain value - for example;给定每个字母都有一定的价值——例如;
letters = [F, G, H, F, J, K]字母 = [F, G, H, F, J, K]
Where F is 10, G is 20, H is 30, J is 40 and K is 50.其中 F 为 10,G 为 20,H 为 30,J 为 40,K 为 50。
I made a semi-working program using if/elif/else and giving each letter a variable of the number, but I was just wondering if there's a more efficient way of doing this, though without the uses of dictionaries.我使用 if/elif/else 制作了一个半工作程序,并为每个字母提供了一个数字变量,但我只是想知道是否有更有效的方法来做到这一点,尽管没有使用字典。
Thanks for any help guys.感谢您的帮助。
Here is a simple and clear way, you need to store your letters to numbers mappings in a dictionary, and then given any list of letters, you can easily convert to the numbers they are mapped to.这是一种简单明了的方法,您需要将字母到数字的映射存储在字典中,然后给定任何字母列表,您可以轻松地将其转换为它们映射到的数字。
letter_dict = {'F':10,'G':20,'H':30,'J':40,'K':50}
letter_lst = ['F','J','H','K','G']
number_lst = [letter_dict[letter] for letter in letter_lst]
print(number_lst)
Output: Output:
[10, 40, 30, 50, 20]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.