用Python映射函数和Dictionary以求和ASCII值
我们想使用映射函数和字典为句子中的每个单词以及整个句子计算ASCII总和。例如,如果我们有句子-
"hi people of the world"
单词的相应ASCII总和为:209645213321321552
而他们的总数将是: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
热门推荐
10 新年简短的英文祝福语
11 保持快乐祝福语大全简短
12 关于早晨的祝福语简短
13 生日祝福语简短蛋糕上
14 小孩想说的祝福语简短
15 祝女儿出嫁简短祝福语
16 二胎祝福语简短霸气
17 给生病公公祝福语简短
18 送给同桌的祝福语简短