加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

除了一个之外,在python dict中对值进行求和

发布时间:2020-12-20 12:28:49 所属栏目:Python 来源:网络整理
导读:有没有办法在 python dict中对所有值求和,除了使用选择器 x = dict(a=1,b=2,c=3) np.sum(x.values())6 ? 我目前的解决方案是基于循环的解决方案 x = dict(a=1,c=3) y = 0 for i in x:... if 'a' != i:... y += x[i]... y5 编辑: import numpy as npfrom sc
有没有办法在 python dict中对所有值求和,除了使用选择器

>>> x = dict(a=1,b=2,c=3)
>>> np.sum(x.values())
6


我目前的解决方案是基于循环的解决方案

>>> x = dict(a=1,c=3)
>>> y = 0
>>> for i in x:
...     if 'a' != i:
...             y += x[i]
... 
>>> y
5

编辑:

import numpy as np
from scipy.sparse import *
x = dict(a=csr_matrix(np.array([1,0]).reshape(3,3)),b=csr_matrix(np.array([0,1]).reshape(3,c=csr_matrix(np.array([0,3)))
y = csr_matrix((3,3))
for i in x: 
    if 'a' != i:
        y = y + x[i]
print y

返回(2,2)2.0

print np.sum(value for key,value in x.iteritems() if key != 'a')

加薪

File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-    packages/numpy/core/fromnumeric.py",line 1446,in sum
    res = _sum_(a)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/compressed.py",line 187,in __radd__
    return self.__add__(other)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/compressed.py",line 173,in __add__
    raise NotImplementedError('adding a scalar to a CSC or CSR '
NotImplementedError: adding a scalar to a CSC or CSR matrix is not supported

解决方法

您需要为sum方法提供累加器或初始值:

sum((value for key,value in x.iteritems() if key != 'a'),csr_matrix((3,3)))

请注意,这是使用内置和方法.它与基于循环的解决方案几乎完全相同.

使用np.sum将不起作用,因为np.sum不传递out参数,并且无论如何都是为密集矩阵设计的.

np.sum((value for key,out=csr_matrix((3,3)))    # doesn't work

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读