简体   繁体   English

将地图与queue.put()一起使用?

[英]Using map with queue.put()?

To load a list into a queue in Python, I found this code snippet which failed to work. 要将列表加载到Python中的队列中,我发现此代码段无法正常工作。 No items were added to the queue: 没有项目添加到队列:

from queue import Queue
my_list = [1,2,3,4,5,6,7,8,9,10]
q = Queue()

# This code doesn't work
map(q.put, my_list)
q.qsize() # Returns zero, which is unexpected

The more verbose solution: 更详细的解决方案:

for num in my_list:
    q.put(num)
print(q.qsize())  # returns 10 as expected

works as expected. 可以正常工作。 What am I missing here? 我在这里想念什么?

map(q.put, my_list) just returns an iterator. map(q.put, my_list)仅返回一个迭代器。 Unless you iterate through it, your queue q wont be populated 除非您进行迭代,否则不会填充您的队列q

>>> q = Queue()
>>> itr = map(q.put, my_list)
>>> q.qsize()
0
>>> _ = list(map(q.put, my_list))
>>> q.qsize()
10

That is not how map works: map不是这样工作的:

from queue import Queue
l = [i for i in range(10)]
q = Queue()
x = map(q.put, l)
q.qsize()
# Output: 0
for _ in x:
    pass
q.qsize()
# Output: 10

You can get what you want using a ThreadPool : 您可以使用ThreadPool获得所需的内容:

from queue import Queue
from multiprocessing.pool import ThreadPool
l = [i for i in range(10)]
p = ThreadPool()
q = Queue()
_ = p.imap_unordered(q.put, l)
q.qsize()
# Output: 10

If you want other built-ins: 如果您需要其他内置插件:

# list comprehension (essentially what map is equivalent to)
_ = [q.put(i) for i in l]

# the `any` method:
_ = any(q.put(i) for i in l)

I am not sure why that is not working for you. 我不确定为什么这对您不起作用。 Maybe your version of python, I am on 2.7.6 也许您的python版本是2.7.6

from queue import Queue
my_list = [1,2,3,4,5,6,7,8,9,10]
q = Queue()

# This code doesn't work
map(q.put, my_list)
q.qsize()

print q.qsize() # 10

while not q.empty():
    print q.get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM