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