更改多处理列表

2024-09-29 23:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在Python2.7中遇到了一个奇怪的行为。你知道吗

>>> import multiprocessing as mp
>>> lst = mp.Manager().list()
>>> lst.append([1,2])
>>> lst.append([3,4])
>>> print(lst)
[[1, 2], [3, 4]]
>>> lst[0][1] = 123
>>> print(lst)
[[1, 2], [3, 4]]     

嗯?为什么多重处理列表的第一个元素没有更改?它适用于普通列表!你知道吗

让我们换一种方式试试。你知道吗

>>> lst[0] = [1,123]
>>> print(lst)
[[1, 123], [3, 4]]

好吧,至少我有个解决办法。但是为什么第一个代码片段中的assignmentlst[0][1] = 123不起作用呢?你知道吗


Tags: 代码import元素列表as方式managermp
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:18

我试图解决你的问题,以下是我遇到的情况:

Note Modifications to mutable values or items in dict and list proxies will not be propagated through the manager, because the proxy has no way of knowing when its values or items are modified. To modify such an item, you can re-assign the modified object to the container proxy:

多亏了this question。你知道吗

因此,似乎不是数据结构本身的问题,而是管理它的问题。因此,我根据the docs创建了一个进程:

import multiprocessing as mp

def targ(*args, **kwargs):
  print('Args: {}'.format(args[0]))
  args[0][0].pop()
  args[0][0].append(123)
  print('Args: {}'.format(args[0]))

manager = mp.Manager()
lst = manager.list()
lst.append([1, 2])
lst.append([3, 4])

print(lst)

proc = mp.Process(target=targ, args=(lst,))
proc.start()
proc.join()

print(lst)

给我以下结果:

$ python3 main.py 
[[1, 2], [3, 4]]
Args: [[1, 2], [3, 4]]
Args: [[1, 123], [3, 4]]
[[1, 123], [3, 4]]

当我尝试使用args[0][0][1] = 123进行分配时,没有发生任何更改,因此需要一种解决方法或其他方法。你知道吗

相关问题 更多 >

    热门问题