如何在Python3中根据给定数值列表获取字符串各字符对应值?
Problem Statement
I need to retrieve the corresponding values from a 26-element numerical list for each character in a lowercase string. The list number_list is ordered such that its first element maps to 'a', the second to 'b', and so on, with the last element corresponding to 'z'.
Example 1
Input:
number_list = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7] string = 'abc'
Output:
[1, 3, 1]
Example 2
Input:
number_list = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7] string = 'zaba'
Output:
[7, 1, 3, 1]
How can I implement this in Python 3.x?
Solution
The key here is converting each character to its matching index in number_list. Since 'a' has an ASCII value of 97, subtracting ord('a') from the ASCII value of any lowercase letter gives us the correct 0-based index (0 for 'a', 1 for 'b', ..., 25 for 'z').
Here are three simple, effective approaches:
1. List Comprehension (Most Concise)
This is the cleanest way to get the result in a single line:
number_list = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7] string = 'zaba' result = [number_list[ord(char) - ord('a')] for char in string] print(result) # Output: [7, 1, 3, 1]
2. For Loop (Explicit for Beginners)
If you prefer a step-by-step breakdown, a for loop makes the logic easy to follow:
number_list = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7] string = 'abc' result = [] for char in string: # Calculate the index for the character char_index = ord(char) - ord('a') result.append(number_list[char_index]) print(result) # Output: [1, 3, 1]
3. Using map() Function
You can also use map() to apply the index lookup to every character in the string:
number_list = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7] string = 'zaba' result = list(map(lambda char: number_list[ord(char) - ord('a')], string)) print(result) # Output: [7, 1, 3, 1]
Important Notes
- Ensure your input string only contains lowercase letters—if there are uppercase characters or non-alphabet symbols, you'll get an
IndexError(since the calculated index will be outside the bounds ofnumber_list). To handle uppercase, convert the string to lowercase first withstring.lower(). - The
number_listmust have exactly 26 elements to cover all letters from 'a' to 'z'.
内容的提问来源于stack exchange,提问作者user9342203

