Calculating sum of a string using lettervalues

2019-09-19 12:24发布

问题:

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?

回答1:

lettermap = {
  'o': 1,
  'b': 2,
   ...
}

print sum(lettermap[c] for c in 'coffee')


回答2:

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

>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> sum(dct[ch] for ch in 'aab')
4