Skip to main content
 首页 » 编程设计

python之折叠笛卡尔积的结果

2025年05月04日14soundcode

用python计算笛卡尔积非常简单。只需要使用 itertools.product

>>> source = [['a', 'b', 'c'], [1, 2, 3]] 
>>> list(itertools.product(*source)) 
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] 

但是我找不到反向操作。如何从产品的结果中找到来源 [['a', 'b', 'c'], [1, 2, 3]]。有谁知道通用解决方案吗?

我很感激任何建议。

请您参考如下方法:

这只是部分解决方案,但假设您确定结果是由 itertools.product 生成的有效笛卡尔积,并且它超过了 列表不同的值

>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)] 
[['a', 'b', 'c'], [1, 2, 3]] 

这里我们简单地使用 zip(*...) 习惯用法来解压元组,然后使用 OrderedDict 代替 OrderedSet将它们还原为它们的唯一值。

此方法适用于具有不同值的更大 itertools.product。例如:

>>> source = [['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]] 
>>> cartesian_product = itertools.product(*source) 
>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)] 
[['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]]