简体   繁体   English

一组python的幂集和笛卡尔积

[英]Power set and Cartesian Product of a set python

I am trying to find the cartesian product of two different sets.我试图找到两个不同集合的笛卡尔积。 I can not find anything on the web about cartesian products of sets it's either of list or dictionaries.我在网上找不到任何关于集合的笛卡尔积的任何东西,它要么是列表,要么是字典。

Also power set is very confusing.电源组也很混乱。

Neither one of these are in my book I have been using.我一直在使用的书中没有一个。

Could one of yall point me to the right direction.你们中的一个能否指出我正确的方向。

For the Cartesian product, check outitertools.product .对于笛卡尔积,请查看itertools.product

For the powerset, the itertools docs also give us a recipe:对于 powerset, itertools文档也给了我们一个秘诀:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

For example:例如:

>>> test = {1, 2, 3}
>>> list(powerset(test))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(product(test, test))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM