Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itertools.chain to chain an iter list?

import itertools
def _yield_sample():
    it = iter(itertools.combinations('ABCD', 2))
    it2 = iter(itertools.combinations('EFGH', 3))
    itc = itertools.chain(it,it2)
    for x in itc:
        yield x

def main():
    for x in _yield_sample():
        print x

This works to print the combinations.

>>> 
('A', 'B')
('A', 'C')
('A', 'D')
...

But this:

def __position_combination(_count = [2,3,4,5]):
    its = []
    for ct in _count:
        it = iter(itertools.combinations('ABCDEFG', ct))
        its.append(it)
    itc = itertools.chain(its)
    for x in itc:
        yield x

def main():
    for x in __position_combination():
        print x

will not, it will print out

>>> 
<itertools.combinations object at 0x02179210>
<itertools.combinations object at 0x02179240>
<itertools.combinations object at 0x02179270>

I have to rewrite code to make it works as demanded.

itc = itertools.chain(*its)

Here is my question:

itertools.chain(iter, iter, iter)  vs    itertools.chain(*[iter,iter,iter])

What is the different between them? According to documentation the itertools.chain does:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

So, why does itertools.chain(iter, iter, iter) also works here?
Does it means iter, iter, iter = *(iter, iter, iter) ?

like image 649
user478514 Avatar asked Mar 08 '11 06:03

user478514


2 Answers

Yes.

But itertools.chain.from_iterable().

like image 167
Ignacio Vazquez-Abrams Avatar answered Oct 16 '22 21:10

Ignacio Vazquez-Abrams


is it means iter, iter, iter = *(iter, iter, iter) ?

Not by itself. Argument unpacking only works when calling a function, so the following two calls are equivalent:

f(1,2,3)
f(*[1,2,3])

But *[1,2,3] won't compile unless it's a part of a call. You can mix normal (positional) arguments with unpacked ones:

f(1,*[2,3])

so the above is also equivalent to the previous two calls.

like image 4
Rafał Dowgird Avatar answered Oct 16 '22 22:10

Rafał Dowgird