折叠笛卡尔积的结果



用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]]

最新更新