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

更新於:20-6-2020

654 瀏覽量

開始你的 職業生涯

透過完成課程取得認證

入門
廣告
© . All rights reserved.