python构建字典英文与ascii_用Python映射函数和Dictionary以求和ASCII值

我们想使用映射函数和字典为句子中的每个单词以及整个句子计算ASCII总和。例如,如果我们有句子-"hi people of the world"

单词的相应ASCII总和为:209 645 213 321 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值