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

标签 python list dictionary

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

假设我有字典

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

关于python - 如何对包含字典元素的列表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16877831/

相关文章:

java - 动态读取Excel并存储在 map 中

excel - 如何访问嵌套字典的键?

python - 如何居中绘制 3d 曲面图?

python - 如何删除列表中的数字并保持元素的重置? Python

android - 用于处理联系人中的地址新闻的 Intent 过滤器?

list - Prolog-映射(关联数组)

python - 为什么Python3 typing.List 是list 的子类,而list 又是typing.List 的子类?

python - 带有缺失/不完整标题或不规则列数的 read_csv

python - 对矩阵中的多个数组连续执行高斯拟合并保存结果

Python BS4 表解析返回空列表