You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中根据给定数值列表获取字符串各字符对应值?

Python 3.x: Map Lowercase Characters to Corresponding Values from a 26-Element List

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 of number_list). To handle uppercase, convert the string to lowercase first with string.lower().
  • The number_list must have exactly 26 elements to cover all letters from 'a' to 'z'.

内容的提问来源于stack exchange,提问作者user9342203

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:39:14