Python - 字典值字符串长度总和
有时,在使用Python字典时,我们可能会遇到问题,我们需要对作为字典值存在的所有字符串长度进行求和。这可以应用于许多领域,例如 Web 开发和日常编程。让我们讨论可以执行此任务的某些方式。
方法 #1:使用sum() + generator expression + len()
上述功能的组合可用于执行此任务。在此,我们使用 len() 计算长度,使用 sum() 求和,使用生成器表达式进行迭代。
# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using sum() + len() + generator expression
from collections import ChainMap
# initializing dictionary
test_dict = {'gfg' : '2345',
'is' : 'abcde',
'best' : 'qwerty'}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Dictionary values String Length Summation
# Using sum() + len() + generator expression
res = sum((len(val) for val in test_dict.values()))
# printing result
print("The string values length summation : " + str(res))
输出 :
The original dictionary is : {‘is’: ‘abcde’, ‘best’: ‘qwerty’, ‘gfg’: ‘2345’}
The string values length summation : 15
方法 #2:使用map() + len() + sum()
这将执行类似于上述函数的任务。唯一的区别是使用 map() 而不是生成器表达式执行迭代。
# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using map() + len() + sum()
# initializing dictionary
test_dict = {'gfg' : '2345',
'is' : 'abcde',
'best' : 'qwerty'}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Dictionary values String Length Summation
# Using map() + len() + sum()
res = sum(map(len, test_dict.values()))
# printing result
print("The string values length summation : " + str(res))
输出 :
The original dictionary is : {‘is’: ‘abcde’, ‘best’: ‘qwerty’, ‘gfg’: ‘2345’}
The string values length summation : 15