一只萌萌小番薯
使用内置函数sum和生成器表达式:>>> p = {'A' : 1, 'B' : 2, 'C' : 3}>>> q = ['A','B']#using generator expression>>> sum(p.get(x,0) for x in q)3#using list comprehension, not memory efficient>>> sum( [p.get(x,0) for x in q] )3如果在q中找不到任何元素,p则dict.get它将返回默认值0,因此不会引发任何错误。帮助dict.get:>>> print dict.get.__doc__D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.该列表理解的版本大致等同于:sums = []for x in q: #loop over each item in q sums.append(p.get(x,0)) #fetch the value of item from p and append it to sums print sum(sums) # sum the list sums(p.get(x,0) for x in q)是一个生成器表达式,而不是在内存中生成整个列表,而是一次返回一个值。summ = 0for x in q: summ += p.get(x,0)print summ