问题
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