折叠笛卡尔积的结果

时间:2016-10-10 09:10:48

标签: python itertools

用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]]。有谁知道通用解决方案?

我感谢任何建议。

1 个答案:

答案 0 :(得分:6)

它只是一个部分解决方案,但假设您知道某些结果是由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]]
相关问题