python 连接生成器和项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2443252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate generator and item
提问by TarGz
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.
问题是,据我所知,这会创建 3 个元组,只是为了立即丢弃它们,并且还会复制“my_generator”中的项目一次。
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
但我想知道是否可以在没有该函数定义的情况下做到这一点
回答by Mark Rushakoff
itertools.chain
treats several sequences as a single sequence.
itertools.chain
将多个序列视为一个序列。
So you could use it as:
所以你可以将它用作:
import itertools
def my_generator():
yield 1
yield 2
for i in itertools.chain(my_generator(), [5]):
print i
which would output:
这将输出:
1
2
5
回答by Ignacio Vazquez-Abrams
回答by Arkady
Try itertools.chain(*iterables)
. Docs here: http://docs.python.org/library/itertools.html#itertools.chain
试试itertools.chain(*iterables)
。文档在这里:http: //docs.python.org/library/itertools.html#itertools.chain