如何从字典中返回python sum值

时间:2015-10-24 12:27:40

标签: python dictionary

我创建了一个键和值的字典,每个字母都有自己的value。如下所示:

num = {
    'a': '1',
    'b': '2',
    'c': '3',
    'd': '4',
    'e': '5',
    'f': '6',
    'g': '7',
    'h': '8',
    'i': '9',
    'j': '10',
    'k': '11',
    'l': '12',
    'm': '13',
    'n': '14',
    'o': '15',
    'p': '16',
    'q': '17',
    'r': '18',
    's': '19',
    't': '20',
    'u': '21',
    'v': '22',
    'w': '23',
    'x': '24',
    'y': '25',
 'z': '26'}

我想接受用户输入的通知。例如树木。

然后将其分解为个人letters。请参阅我的dictionary,然后根据字典返回其值的总和。

3 个答案:

答案 0 :(得分:2)

你可以这样做:

num = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
name = raw_input("Enter name: ")
L = list(name)

print sum([int(num[i]) for i in L])

输入:

Enter name: mary

输出:

57

答案 1 :(得分:0)

试一试:

di = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12', 'm':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25' ,'z':'26'}
p = raw_input()
l = map(int, [di[x] for x in p])
print sum(l)

答案 2 :(得分:0)

l = list(input)
print sum([int(num[i] for i in l])