3

有没有办法对python dict中的所有值求和,除了一个通过使用选择器

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

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

>>> x = dict(a=1, b=2, 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,0,0,0,0,0,0,0]).reshape(3,3)),      b=csr_matrix(np.array([0,0,0,0,0,0,0,0,1]).reshape(3,3)), c=csr_matrix(np.array([0,0,0,0,0,0,0,0,1]).reshape(3,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
4

3 回答 3

8

您可以遍历 dict 为该sum方法创建一个生成器:

np.sum(value for key, value in x.iteritems() if key != 'a')
于 2012-07-30T09:41:03.867 回答
4

尝试:

np.sum(x.values()) - x['a']
于 2012-07-30T09:56:53.157 回答
2

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

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

请注意,这是使用内置sum方法。它的效果几乎与基于循环的解决方案相同。

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

np.sum((value for key, value in x.iteritems() if key != 'a'),
       out=csr_matrix((3, 3)))    # doesn't work
于 2012-07-30T10:20:03.910 回答