像
这样的东西{A: 3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847}, {B: 92374, 324, 345, 345, 45879, 34857987, 3457938457), {C: 23874923874987, 2347}
如何将其减少到
{A: 2304923094820398}, {B: 2374923784897}, {C: 29348239847239847}
值显然不准确。我只想以非耗时的方式添加所有值。
答案 0 :(得分:2)
d = [{'A': [3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847]}, {'B': [92374, 324, 345, 345, 45879, 34857987, 3457938457]}, {'C': [23874923874987, 2347]}]
[{x.keys()[0]:sum(x.values()[0])} for x in d]
答案 1 :(得分:1)
这样的事情:
a={'a':range(100), 'b':range(200)}
b={}
for k,v in a.iteritems():
b[k]=sum(v)
print b
给出
{'a': 4950, 'b': 19900}
答案 2 :(得分:0)
假设值在列表中,例如:
d = {A: [3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847]}, {B: [92374, 324, 345, 345, 45879, 34857987, 3457938457]), {C: [23874923874987, 2347]}
然后:
new_d = []
for i in d:
new_d.append(dict([(k,sum(v)) for k,v in i.itervalues()]))
答案 3 :(得分:0)
如果你有很多很多很多值,这样的东西可能会起作用(假设“词典列表”你的意思是“列表字典”,因为有一个单键/值对词典的大列表会是愚蠢的,因此值存储在dict
{'A': [3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847], 'B': [92374, 324, 345, 345, 45879, 34857987, 3457938457], ...}
}中:
from multiprocessing import Process, Lock
def sumfunc(lock, key, values):
total = sum(values)
lock.acquire()
print(key + ':', total) # The actual code would be better off utilizing shared multiprocessing.Array objects, but I haven't used them before so am not sure quite how you set them up so decided to leave that aside for now as this is just a theoretical example.
lock.release()
if __name__ == '__main__':
lock = Lock()
for key, values in dict_of_values_to_sum.items():
Process(target=sumfunc, args=(lock, key, values)).start()
答案 4 :(得分:0)
如果你有很多值,我可能会使用numpy并添加一个向量。
所以,像
a = numpy.arange(10, 2000000)
total = numpy.sum(a)
没有更多,没有更少:)
答案 5 :(得分:0)
d = [{'A': [3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847]}, {'B': [92374, 324, 345, 345, 45879, 34857987, 3457938457]}, {'C': [23874923874987, 2347]}]
abc = {}
for x in d:
for k, v in x.iteritems():
abc[k] = reduce(lambda x,y: x+y, v)