Calculating sum of a string using lettervalues

2019-09-19 12:45发布

I have spent way too much time trying to solve what seems to be a pretty easy task.

I have assigned some letters/variables with different values. Ex:

o,b,c,d,e,f = 1,2,3,4,5,6

and I want to find the "sum" of a string containing any of the letters, like this:

'coffee' = 3+1+6+6+5+5

Is there an easy/fast way to do this?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-19 12:59
lettermap = {
  'o': 1,
  'b': 2,
   ...
}

print sum(lettermap[c] for c in 'coffee')
查看更多
爷的心禁止访问
3楼-- · 2019-09-19 13:05

You need the structure of a dict and sum():

>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> sum(dct[ch] for ch in 'aab')
4
查看更多
登录 后发表回答