用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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短