Python 中的 Map 函数和字典用于对 ASCII 值求和
pythonprogrammingserver side programming更新于 2024/3/25 10:33:00
我们想使用 map 函数和字典计算句子中每个单词和整个句子的 ASCII 总和。例如,如果我们有句子 −
"hi people of the world"
这些单词对应的 ASCII 总和为:209 645 213 321 552
它们的总和为:1940。
我们可以使用 map 函数通过 ord 函数查找单词中每个字母的 ASCII 值。然后使用 sum 函数我们可以将其求和。对于每个单词,我们可以重复此过程并得到最终的 ASCII 值总和。
示例
sent = "hi people of the world" words = sent.split(" ") result = {} # 计算每个单词的 ASCII 值之和 for word in words: result[word] = sum(map(ord,word)) totalSum = 0 # 使用字典创建一个包含单词 ASCII 值之和的数组 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 句子中所有 ASCII 值的总数:1940