Python – 使用字典评分矩阵
有时,在处理Python记录时,我们可能会遇到需要解决Python矩阵记录中的评分问题。这意味着将字典的每个键与其值映射到每行的总分数。这种问题可以在游戏和网络开发领域有应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[‘gfg’, ‘best’], [‘geeks’], [‘is’, ‘for’]]
Output : [18, 15, 12]
Input : test_list = [[‘gfg’, ‘geeks’, ‘CS’]]
Output : [20]
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们迭代矩阵元素并使用字典执行值替换并执行行求和。
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using loop
# initializing list
test_list = [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {'gfg' : 5, 'is' : 10, 'best' : 13, 'for' : 2, 'geeks' : 15}
# Scoring Matrix using Dictionary
# Using loop
res = []
for sub in test_list:
sum = 0
for val in sub:
if val in test_dict:
sum += test_dict[val]
res.append(sum)
# printing result
print("The Row scores : " + str(res))
输出 :
The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
The Row scores : [28, 32]
方法 #2:使用列表理解 + sum()
这是解决此问题的另一种方法。在此,我们使用 sum() 执行求和,列表推导用于迭代和分数分配。
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
# initializing list
test_list = [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {'gfg' : 5, 'is' : 10, 'best' : 13, 'for' : 2, 'geeks' : 15}
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
res = [sum(test_dict[word] if word.lower() in test_dict else 0 for word in sub) for sub in test_list]
# printing result
print("The Row scores : " + str(res))
输出 :
The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
The Row scores : [28, 32]