Put multiple items in a python queue

十年热恋 提交于 2019-12-07 03:06:39

问题


Suppose you have an iterable items containing items that should be put in a queue q. Of course you can do it like this:

for i in items:
    q.put(i)

But it feels unnecessary to write this in two lines - is that supposed to be pythonic? Is there no way to do something more readable - i.e. like this

q.put(*items)

回答1:


Using the built-in map function :

map(q.put, items)

It will apply q.put to all your items in your list. Useful one-liner.


For Python 3, you can use it as following :

list(map(q.put, items))

Or also :

from collections import deque
deque(map(q.put, items))

But at this point, the for loop is quite more readable.




回答2:


q.extend(items)

Should be simple and Pythonic Enough

If you want it at the front of the queue

q.extendleft(items)

Python Docs:

https://docs.python.org/2/library/collections.html#collections.deque.extend




回答3:


What's unreadable about that?

for i in items:
    q.put(i)

Readability is not the same as "short", and a one-liner is not necessarily more readable; quite often it's the opposite.

If you want to have a q.put(*items)-like API, consider making a short helper function, or subclassing Queue.



来源:https://stackoverflow.com/questions/31987207/put-multiple-items-in-a-python-queue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!