简体   繁体   中英

sum over values in python dict except one

Is there a way to sum over all values in a python dict except one by using a selector in

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

? My current solution is a loop based one:

>>> 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

returns (2, 2) 2.0

and

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

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

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

尝试:

np.sum(x.values()) - x['a']

You need to supply an accumulator or initial value for the sum method:

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

Note that this is using the builtin sum method. It's almost identical in effect to your loop-based solution.

Using np.sum won't work because np.sum doesn't pass the out argument, and is anyway designed for dense matrices.

np.sum((value for key, value in x.iteritems() if key != 'a'),
       out=csr_matrix((3, 3)))    # doesn't work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM