Map 函式和 Python 中的 Dictionary 用於計算 ASCII 值總和
我們想要計算句子中每個單詞以及整個句子的 ASCII 總和,並使用 map 函式和字典。例如,如果我們有以下句子 −
"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 = {} # 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
廣告