Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Map function และ Dictionary ใน Python หาผลรวมค่า ASCII

ต้องการคำนวณผลรวม ASCII สำหรับแต่ละคำในประโยคและประโยคทั้งหมดด้วย map function และ dictionary เช่น ประโยค

"hi people of the world"

ผลรวม ASCII ของคำแต่ละคำคือ: 209 645 213 321 552

ผลรวมทั้งหมด: 1940

ใช้ map หา ASCII ของแต่ละตัวอักษรด้วย ord แล้ว sum รวม สำหรับแต่ละคำทำซ้ำ

ตัวอย่าง

sent = "hi people of the world"
words = sent.split(" ")
result = {}
# คำนวณผลรวม ASCII ทุกคำ
for word in words:
    result[word] = sum(map(ord, word))
totalSum = 0
# สร้างอาร์เรย์ผลรวม ASCII ของคำจาก 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