【问题标题】:Why can't I iterate a (multiprocessing) manager list?为什么我不能迭代(多处理)管理器列表?
【发布时间】:2015-11-15 14:29:31
【问题描述】:

我有一个由经理列表组成的数组,例如:

[<ListProxy object, typeid 'list' at 0x177d350>, <ListProxy object, typeid 'list' at 0x177d390>, ...]

并尝试将其转换为纯列表。我的考虑如下:

y=[]
for i in my_manager_list_content:
    for j in i:
        y.append(float(j))
print y #This works

print [next(iter(i[:]))  for i in my_manager_list_content] #Why doesn't this work?

我怎么能在 oneliner 中做到这一点?

【问题讨论】:

  • [float(i) for j in my_manager_list_content for i in j]?
  • 谢谢。这就是解决方案!

标签: python python-multiprocessing


【解决方案1】:

解释为什么您的代码不起作用。 iter() 接受一个可迭代对象并返回一个交互器。 next() 接受迭代器并返回下一个元素。在您的代码中,当您从my_manager_list_content 中取出一个元素时,您只能使用next 从中取出第一个元素,然后继续使用my_manager_list_content 的第二个元素。这可以通过以下代码来说明:(@Kevin Guan 解决方案的扩展)

from multiprocessing import Process, Manager

def f(ll, l):
    for ii in range(3):
        ll.append(l)

if __name__ == '__main__':
    with Manager() as manager:
        ll = manager.list()
        l = manager.list(range(3))
        p = Process(target=f, args=(ll, l))
        p.start()
        p.join()

        print([float(ii) for jj in ll for ii in jj])
        print([next(iter(ii)) for ii in ll])

我得到了

[0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0]
[0, 0, 0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2011-02-05
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多