div*_*ero 2 python iterator scope functional-programming function-composition
我有一个元组列表,我需要通过添加两个元素来扩展它,每个元素来自一个列表.所以我有[(1, 2, 3)]两个迭代器it1 = (i for i in ['a1', 'a2'])和it2 = (i for i in in ['b1', 'b2']).结果应该是[(1, 2, 3, 'a1', 'b1'), (1, 2, 3, 'a1', 'b2'), (1, 2, 3, 'a2', 'b1'), (1, 2, 3, 'a2', 'b2')].
如果我使用上面显示的迭代器它不起作用.但是,如果我使用列表它是有效的.这是代码:
def get_iters():
return ((i for i in ['a1', 'a2']), (i for i in ['b1', 'b2']))
def get_lists():
return ([i for i in ['a1', 'a2']], [i for i in ['b1', 'b2']])
def compose(lst_of_tuples, iter=True):
iters = get_iters() if iter else get_lists()
for it in iters:
lst_of_tuples = [t + (i,) for t in lst_of_tuples for i in it]
return lst_of_tuples
print compose([(1,2,3)], True)
# WRONG!???? (what happened to the 'a2' part of it?)
# prints: [(1, 2, 3, 'a1', 'b1'), (1, 2, 3, 'a1', 'b2')]
print compose([(1,2,3)], False)
# RIGHT!! prints: [(1, 2, 3, 'a1', 'b1'), (1, 2, 3, 'a1', 'b2'), (1, 2, 3, 'a2', 'b1'), (1, 2, 3, 'a2', 'b2')]
Run Code Online (Sandbox Code Playgroud)
我想不出这就是为什么会这样的原因.谁能解释一下?
Iterables只能迭代一次,之后就会耗尽.
在for循环中第二次循环遍历给定的iterable时,不再返回任何元素.
itertools.product()首先循环,然后遍历元组列表以生成输出:
from itertools import product
def compose(lst_of_tuples, iter=True):
iters = get_iters() if iter else get_lists()
return [t + i for i in product(*get_iters()) for t in lst_of_tuples]
Run Code Online (Sandbox Code Playgroud)
这会产生:
>>> print compose([(1,2,3)], True)
[(1, 2, 3, 'a1', 'b1'), (1, 2, 3, 'a1', 'b2'), (1, 2, 3, 'a2', 'b1'), (1, 2, 3, 'a2', 'b2')]
>>> print compose([(1,2,3)], False)
[(1, 2, 3, 'a1', 'b1'), (1, 2, 3, 'a1', 'b2'), (1, 2, 3, 'a2', 'b1'), (1, 2, 3, 'a2', 'b2')]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1581 次 |
| 最近记录: |