要将列表加载到Python中的队列中,我发现此代码片段无法正常工作。没有项目添加到队列中:
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
更详细的解决方案:
for num in my_list:
q.put(num)
print(q.qsize()) # returns 10 as expected
按预期工作。我在这里想念什么?
答案 0 :(得分:4)
map(q.put, my_list)
仅返回迭代器。除非您进行迭代,否则队列q
不会被填充
>>> q = Queue()
>>> itr = map(q.put, my_list)
>>> q.qsize()
0
>>> _ = list(map(q.put, my_list))
>>> q.qsize()
10
答案 1 :(得分:0)
map
的工作方式不是这样:
delete()
您可以使用ThreadPool
获得所需的内容:
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
如果您需要其他内置功能:
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
答案 2 :(得分:0)
我不确定为什么这对您不起作用。也许是您的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()