我们的想法是,这两个列表都是比较所有潜在的
组合和所有选项将附加到新列表中。
对于可变数量的变量,可以使用字典。
要计算两个列表的成对笛卡尔积,可以使用
itertools.product
具有
map
是的。然后使用字典理解来映射独特的组合:
from itertools import chain, product
products = set(chain.from_iterable(map(product, List1, List2)))
res = {smoothie: f'Smoothie{idx}' for idx, smoothie in enumerate(products, 1)}
结果:
{('apple', 'banana'): 'Smoothie7',
('apple', 'coconut'): 'Smoothie3',
('apple', 'grape'): 'Smoothie13',
('apple', 'kiwi'): 'Smoothie2',
('apple', 'orange'): 'Smoothie4',
('banana', 'apple'): 'Smoothie9',
('banana', 'coconut'): 'Smoothie8',
('banana', 'kiwi'): 'Smoothie11',
('banana', 'orange'): 'Smoothie17',
('blueberry', 'apple'): 'Smoothie16',
('blueberry', 'kiwi'): 'Smoothie15',
('coconut', 'blueberry'): 'Smoothie10',
('grape', 'blueberry'): 'Smoothie12',
('kiwi', 'apple'): 'Smoothie21',
('kiwi', 'banana'): 'Smoothie1',
('kiwi', 'blueberry'): 'Smoothie23',
('kiwi', 'coconut'): 'Smoothie22',
('kiwi', 'grape'): 'Smoothie20',
('kiwi', 'orange'): 'Smoothie19',
('orange', 'apple'): 'Smoothie6',
('orange', 'banana'): 'Smoothie18',
('orange', 'blueberry'): 'Smoothie14',
('orange', 'coconut'): 'Smoothie5'}
另一方面,如果你在寻找所有的组合
跨子列表
,您可以展开输入列表并使用
product
直接。