無法看到任何方式獲得四個獨立的tupels沒有嵌套(顯式或其他)。
itertools.product將組合列表。
>>> from itertools import product
>>> for thing in suffix:
print(list(map(''.join, product(prefix, thing))))
['blue dog', 'blue shoes', 'blue bike', 'brown dog', 'brown shoes', 'brown bike']
['blue tree', 'blue cat', 'blue car', 'brown tree', 'brown cat', 'brown car']
>>>
這看起來很有趣:
>>> from pprint import pprint
>>> pprint(list(product(prefix, suffix)))
[('blue ', ('dog', 'shoes', 'bike')),
('blue ', ('tree', 'cat', 'car')),
('brown ', ('dog', 'shoes', 'bike')),
('brown ', ('tree', 'cat', 'car'))]
則功能映射到前綴和後綴的產品。
>>> def f(t):
p, s = t
t = product([p], s)
return map(''.join, t)
>>> z = product(prefix, suffix)
>>> y = map(f, z)
>>>
>>> pprint(list(map(tuple, y)))
[('blue dog', 'blue shoes', 'blue bike'),
('blue tree', 'blue cat', 'blue car'),
('brown dog', 'brown shoes', 'brown bike'),
('brown tree', 'brown cat', 'brown car')]
>>>
或者
>>> x = [tuple(thing) for thing in y]
或者不map
>>> def f(t):
p, s = t
t = product([p], s)
return tuple(''.join(thing) for thing in t)
>>> z = product(prefix, suffix)
>>> y = [f(thing) for thing in z]
>>> pprint(y)
[('blue dog', 'blue shoes', 'blue bike'),
('blue tree', 'blue cat', 'blue car'),
('brown dog', 'brown shoes', 'brown bike'),
('brown tree', 'brown cat', 'brown car')]
>>>
這看起來很不錯 - 我試圖直觀地理解這一點,以及如何從左到右或從右到左閱讀它。你有沒有等效的循環建設? – laszlopanaflex
@laszlopanaflex更新! –
謝謝 - 這是我奮鬥了一下,瞭解python如何解釋這些嵌套的語句 - 其他示例顯示從左到右,在這種情況下,我會預料會出現問題,因爲「j」尚未定義。 – laszlopanaflex