代码之家  ›  专栏  ›  技术社区  ›  max

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

  •  1
  • max  · 技术社区  · 6 年前

    为了将一个列表加载到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
    

    按预期工作。我这里缺什么?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Sunitha    6 年前

    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
    
        2
  •  0
  •   Kenan    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()
    
        3
  •  0
  •   pstatix    6 年前

    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
    

    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
    

    # 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)