本文共 747 字,大约阅读时间需要 2 分钟。
我们想使用映射函数和字典为句子中的每个单词以及整个句子计算ASCII总和。例如,如果我们有句子-"hi people of the world"
单词的相应ASCII总和为:209 645 213 321 321 552
而他们的总数将是:1940年。
我们可以使用map函数使用ord函数查找单词中每个字母的ASCII值。然后,使用sum函数我们可以对其进行总结。对于每个单词,我们可以重复此过程并获得ASCII值的最终总和。
示例sent = "hi people of the world"
words = sent.split(" ")
result = {}
# Calculate sum of ascii values for every word
for word in words:
result[word] = sum(map(ord,word))
totalSum = 0
# Create an array with ASCII sum of words using the dict
sumForSentence = [result[word] for word in words]
print ('Sum of ASCII values:')
print (' '.join(map(str, sumForSentence)))
print ('Total of all ASCII values in sentence: ',sum(sumForSentence))
输出结果
这将给出输出-Sum of ASCII values:
209 645 213 321 552
Total of all ASCII values in a sentence: 1940
转载地址:https://blog.csdn.net/weixin_32646781/article/details/113671588 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!