没有嵌套(显式或其他方式),看不到任何获得四个独立元组的方法。
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')]
>>>