将多个项目放入一个python队列中 [英] Put multiple items in a python queue

查看:56
本文介绍了将多个项目放入一个python队列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个可迭代的 items,其中包含应该放入队列 q 中的项目.当然你可以这样做:

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)

但是感觉没有必要分两行写——这应该是pythonic吗?有没有办法做一些更具可读性的事情 - 即像这样

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)

推荐答案

使用内置的map函数:

map(q.put, items)

它会将 q.put 应用到您列表中的所有项目.有用的单行.

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

对于 Python 3,您可以按如下方式使用它:

For Python 3, you can use it as following :

list(map(q.put, items))

或者:

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

但在这一点上,for 循环更具可读性.

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

这篇关于将多个项目放入一个python队列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆