Skip to main content
 首页 » 编程设计

python之如何对包含字典元素的列表求和

2025年05月04日13sharpest

我不确定我问的问题是否正确,但我的意思是:

假设我有字典

p = {'A' : 1, 'B' : 2, 'C' : 3} 

然后我有列表

q = ['A', 'B']        

如何对 q 求和以使结果为 3?

谢谢!

请您参考如下方法:

使用内置函数 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. 

list comprehension版本大致相当于:

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) 是一个 generator expression ,而不是在内存中生成整个列表,它一次返回一个值。

summ = 0 
for x in q: 
    summ += p.get(x,0) 
print summ