有没有一种方法可以在Python字典中使用选择器对除一个值以外的所有值求和?
我的当前解决方案是基于循环的:
EDIT:
>>> 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
EDIT:
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')
raises
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
np.sum
求和来解决此问题。 - DSMnp.sum([value for key, value in x.iteritems() if key != 'a'])
。括号语法是列表推导而不是生成器表达式。 - DSM