列出a,b
a = [5, 8, 9]
b = [6, 1, 0]
我想创建一个生成器gen,以便:
for x in gen:
print x
输出
5, 8, 9, 6, 1, 0
答案 0 :(得分:7)
您可以使用itertools.chain
:
>>> from itertools import chain
>>> a = [5, 8, 9]
>>> b = [6, 1, 0]
>>> it=chain(a,b)
>>> for x in it:
print x,
...
5 8 9 6 1 0
答案 1 :(得分:3)
def chain(*args):
for arg in args:
for item in arg:
yield item
a = [5, 8, 9]
b = [6, 1, 0]
for x in chain(a,b):
print x,
print ', '.join(map(str,chain(a,b)))
答案 2 :(得分:1)
你可以使用 generator expressions 来制作一个荒谬的pythonic和优雅的单行:
>>> a=[5,8,9]
>>> b=[6,1,0]
>>> g=(i for i in a+b)
试验:
>>> for i in g:
print i
5
8
9
6
1
0
或测试#2,如果你真的喜欢在每个项目之间加上逗号,那么:
>>> print ', '.join(map(str,g))
5, 8, 9, 6, 1, 0