지도 기능과 사전을 사용하여 문장의 각 단어와 문장 전체에 대한 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 = {}
# 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