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
這適用於打印組合。itertools.chain鏈接一個iter列表?
>>>
('A', 'B')
('A', 'C')
('A', 'D')
...
但這:
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
不會,它會打印出
>>>
<itertools.combinations object at 0x02179210>
<itertools.combinations object at 0x02179240>
<itertools.combinations object at 0x02179270>
我不得不重寫代碼,使其可以作爲要求。
itc = itertools.chain(*its)
這裏是我的問題:
itertools.chain(iter, iter, iter) vs itertools.chain(*[iter,iter,iter])
它們之間有什麼不同?據documentation 的itertools.chain
做:
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
那麼,爲什麼itertools.chain(iter, iter, iter)
也是在這裏工作?
是否意味着iter, iter, iter = *(iter, iter, iter)
?
感謝您的「參數拆包」 – user478514 2011-03-09 01:47:35