【问题标题】:How do I update the global array from the inside of the function?如何从函数内部更新全局数组?
【发布时间】:2019-12-09 06:53:30
【问题描述】:

我想编写一个返回计数为[1,2,3,4] 的代码,同时保持并行化的for 循环。我正在尝试从increment 函数内部更新全局数组counts,但它永远不会工作并返回[0,0,0,0]。有什么办法可以在并行循环increment 函数时从increment 函数更新counts 数组?

import numpy as np
import multiprocessing as mpp
import timeit

start = timeit.default_timer()

num=5

counts=np.zeros((num,1))

def increment(k):
    global counts
    counts[k]=counts[k]+k

pool = mpp.Pool(4)
pool.map(increment,[k for k in range(0,num)])

print(counts)

stop = timeit.default_timer()

print('Time: ', stop - start) 

【问题讨论】:

标签: python


【解决方案1】:

只需返回counts[k]+k 并将您想要的设置为等于increment(k)

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2016-02-10
    • 2013-03-14
    • 1970-01-01
    • 2018-10-03
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多