while-loop - Python多处理while循环,返回和追加输出
问题描述
我想并行化一个概念上简单的代码,但是我发现的所有其他线程都太复杂了,我不明白如何将它们应用于我的案例,或者即使它们适用。
在我的代码中,通过 while 循环调用具有多个参数的函数,并从循环返回输出和退出条件。我想并行化while循环。我正在使用 Python 3.7.3。
这是一个简化的示例:
import multiprocessing as mp
import numpy as np
import time
def foo(i, arg1, arg2):
n = np.random.rand()
n = arg1*n + arg2
if n > 0.9:
stop = True
else:
stop = False
return [i, n], stop
if __name__ == '__main__':
i = 0
stop = False
output = list()
while not stop:
out, stop = foo(i, 1, 0)
i = i + 1
if not stop:
output.append(out)
print(np.asarray(output))
输出:
[[ 0. 0.25295033]
[ 1. 0.53795096]
[ 2. 0.48774803]
[ 3. 0.09281972]
[ 4. 0.75053227]
[ 5. 0.30367072]
[ 6. 0.57043762]
[ 7. 0.4589554 ]
[ 8. 0.33231446]
[ 9. 0.76805717]
[10. 0.22486246]
[11. 0.69499273]
[12. 0.67616563]]
编辑。我想“碰撞”这个线程,因为这是我真正需要帮助的事情,我不能自己做。Meta-etiquette 说我应该通过为问题添加价值来进行编辑,但我认为我不能添加任何其他内容:我只需要并行化呈现的代码。我真的很感激任何(实际的)反馈。
解决方案
推荐阅读
- html - 如何包装不同高度的物品
- sql - 仅选择满足 where 子句 60% 的行 - SQL Server
- android - GPS 位置数据在 Google 地图上显示不正确
- powershell - Powershell 记录到丢失的网络位置:FileStream 不会重新连接/刷新
- python - 如何在 Python 中捕获我的异常引发并再次反弹
- scala - Pyspark 与 Scala 匹配的结构化流式传输版本
- python - 如何更改格式 xticks 标签并保留热图的颜色条
- c++ - 像离散分布这样的随机分布
- javascript - 每次循环迭代运行的函数,而不是仅最后一次
- python - 将 dict 键分配为数据框名称,将值分配为数据框本身