开发者

itertools.chain to chain an iter list?

开发者 https://www.devze.com 2023-02-15 22:51 出处:网络
import itertools def _yield_sample(): it = iter(itertools.combinations(\'ABCD\', 2开发者_如何学Go))
import itertools
def _yield_sample():
    it = iter(itertools.combinations('ABCD', 2开发者_如何学Go))
    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) ?


Yes.

But itertools.chain.from_iterable().


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消