gpt4 book ai didi

python - 对 python dict 中的值求和,除了一个

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:05 24 4
gpt4 key购买 nike

有没有办法通过在

中使用选择器来对 python 字典中的所有值求和,除了一个
>>> 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

最佳答案

您可以遍历字典来为 sum 方法创建一个生成器:

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

关于python - 对 python dict 中的值求和,除了一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11718852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com