📜  Python|提取字符串的分数列表

📅  最后修改于: 2022-05-13 01:54:29.128000             🧑  作者: Mango

Python|提取字符串的分数列表

有时,在编程时,我们可能会遇到一个问题,即我们为字母表的每个字符指定一个特定的分数,然后根据字符串,仅提取这些分数以进行进一步计算。这可以在游戏领域有应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + ord()
上述功能的组合可用于执行此任务。在此,我们使用列表理解执行元素迭代任务,而 ord() 执行检查必须返回的列表索引的任务。

# Python3 code to demonstrate working of
# Extract Score list of String
# using list comprehension + ord()
  
# initialize list and string 
test_list = [3, 4, 5, 7, 5, 8, 1, 5, 7, 10,
             6, 7, 9, 11, 3, 1, 3, 6, 7, 9,
             7, 4, 6, 4, 2, 1]
               
test_str = "geeksforgeeks"
  
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + str(test_str))
  
# Extract Score list of String
# using list comprehension + ord()
res = [test_list[ord(ele) - 97] for ele in test_str]
  
# printing result
print("The Score list is : " + str(res))
输出 :

方法 #2:使用zip() + ascii_lowercase + dict() + 列表理解
上述功能的组合也可用于执行此任务。在此,将列表元素分数连接到字符的任务由 zip() 完成,列表理解用于输出最终结果。

# Python3 code to demonstrate working of
# Extract Score list of String
# using list comprehension + zip() + ascii_lowercase + dict()
import string
  
# initialize list and string 
test_list = [3, 4, 5, 7, 5, 8, 1, 5, 7, 10,
             6, 7, 9, 11, 3, 1, 3, 6, 7, 9,
             7, 4, 6, 4, 2, 1]
               
test_str = "geeksforgeeks"
  
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + str(test_str))
  
# Extract Score list of String
# using list comprehension + zip() + ascii_lowercase + dict()
temp = dict(zip(string.ascii_lowercase, test_list))
res = [temp[ele] for ele in test_str]
  
# printing result
print("The Score list is : " + str(res))
输出 :