Python 中使用映射函数和字典求 ASCII 值的和
我们想使用映射函数和字典计算句子中每个单词以及整个句子的 ASCII 值总和。例如,如果我们有句子 -
"hi people of the world"
则单词对应的 ASCII 值总和为:209 645 213 321 552
它们的总和为:1940。
我们可以使用映射函数使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP