python - 如何并行洗牌大量项目,python

标签 python algorithm shuffle bigdata

我在 python 上的计算遇到了瓶颈:我需要打乱一个大列表(~10^9 元素)。 当前实现:

import random
random.shuffle(list)

使用这种方法,只涉及一个核心。是否可以并行洗牌一个大列表?

最佳答案

您可以查看 Process类,可以这样举例:

import random
from multiprocessing import Process


def worker_func(variable_1):
# your code

random.shuffle(list_single)

if __name__ == '__main__':
#Create a process list 
process_list = list()

pid = os.getpid()
print('Main Process is started and PID is: ' + str(pid))

#Start Process
list_example = [[1,2,3], [4, 5, 6], [7, 8, 9]]
for list_single in list_example:
    p = Process(target=worker_func, args=(list_single, ))
    p.start()
    child_pid = str(p.pid)
    print('PID is:' + child_pid)
    process_list.append(child_pid)
    child = multiprocessing.active_children()

while child != []:
    time.sleep(1)
    child = multiprocessing.active_children()

如果你想并行运行这些数据,你可以使用multithreadingmultiprocessing .您应该定义辅助函数并在流程中调用它。

关于python - 如何并行洗牌大量项目,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844828/

相关文章:

python - 如何使用 ruamel.yaml 在 Python 中向 YAML 插入注释行?

python - R 中的预测时间分析(数据挖掘算法)

python - 调试 : Shuffle deck of cards in Python/random

python - 对对进行约束的洗牌

javascript - 在访问 Jinja 模板值时使用 JavaScript 变量

python - Pandas 数据帧系列 : check if specific value exists

string - 为什么在文本编辑器的查找功能中选择 "BM algorithm"而不是 "Sunday algorithm"?

javascript - 在网格中查找随机放置的元素 (x,y)

c++ - 如何让我的程序运行得更快?

random - 生成具有 256 个随机位的数字的最佳方法?