2
我有一個元組列表,我需要通過添加兩個元素來擴展它,每個元素都來自一個列表。所以我有[(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')]
。Python:從嵌套迭代器合成列表
如果我使用迭代器,如上所示,它不起作用。但如果我使用它的作品。這裏是代碼:
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')]
我想不出爲什麼會這樣。有人可以解釋嗎?
確定。我現在明白了。迭代器(it1或it2)在迭代了'lst_of_tuples'的第一個元素後用完。所以代碼只能用於第一個元素。如果我在lst_of_tuples中爲t做了[t +(i,),那麼它就起作用了。感謝itertool.product的想法 - 整潔。 – dividebyzero