连接生成器和项目
我有一个生成器(数字)和一个值(数字)。我想迭代这些,就好像它们是一个序列一样:
i for i in tuple(my_generator) + (my_value,)
问题是,据我所知,这会创建 3 个元组,只是为了立即丢弃它们,并且还会复制“my_generator”中的项目一次。
更好的方法是:
def con(seq, item):
for i in seq:
yield seq
yield item
i for i in con(my_generator, my_value)
但我想知道是否可以在没有该函数定义的情况下做到这一点
I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence:
i for i in tuple(my_generator) + (my_value,)
The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my_generator" once.
Better approch would be:
def con(seq, item):
for i in seq:
yield seq
yield item
i for i in con(my_generator, my_value)
But I was wondering whether it is possible to do it without that function definition
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
itertools.chain
将多个序列视为单一序列。所以你可以将它用作:
它将输出:
itertools.chain
treats several sequences as a single sequence.So you could use it as:
which would output:
itertools.chain()
itertools.chain()
尝试itertools.chain(*iterables)。文档在这里: http://docs.python.org/library/itertools.html# itertools.chain
Try
itertools.chain(*iterables)
. Docs here: http://docs.python.org/library/itertools.html#itertools.chain