How to create a two-list generator in python?

List a, b

a = [5, 8, 9] b = [6, 1, 0] 

I want to create a gen generator so that:

 for x in gen: print x 

exits

 5, 8, 9, 6, 1, 0 
+4
source share
3 answers

You can use 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 
+7
source
 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
source

You can use generator expressions for a ridiculously pythonic and elegant single-line interface:

 >>> a=[5,8,9] >>> b=[6,1,0] >>> g=(i for i in a+b) 

Test:

 >>> for i in g: print i 5 8 9 6 1 0 

or test # 2, if you really prefer a comma between each element,

 >>> print ', '.join(map(str,g)) 5, 8, 9, 6, 1, 0 
+1
source

Source: https://habr.com/ru/post/1478860/


All Articles