Home > Blockchain >  List of letters, into a list of numbers
List of letters, into a list of numbers

Time:06-16

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]

Where F is 10, G is 20, H is 30, J is 40 and K is 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.

Thanks for any help guys.

CodePudding user response:

You can use ord:

letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print(letters)
numbers = [(ord(letter) - ord("A")   1) * 10 for letter in letters]
print(numbers)

That starts at A = 10 to Z = 260

CodePudding user response:

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:

[10, 40, 30, 50, 20]
  • Related