Cartesian product of a list of sets in python

笑着哭i 提交于 2019-12-02 04:22:09

问题


I had a list of sets. I do not know the length of the list apriori. I wanted to find the Cartesian product of the sets in the list in some code I'm writing.

For example: I have

list_of_sets=[set(['A']),set(['A','B','C']), set('D','E')];

I want to output a cartesian product of these sets, which would be,

('A', 'A', 'E')
('A', 'A', 'D')
('A', 'C', 'E')
('A', 'C', 'D')
('A', 'B', 'E')
('A', 'B', 'D')

If I knew that the list had size 3 in advance, I could use the following code to generate this cartesian product.

for i in itertools.product(list_of_sets[0],list_of_sets[1],list_of_sets[2]):
    print i

Is there an easy way to do this when I do not know the size of the list?


回答1:


Use itertools.product(*list_of_sets).



来源:https://stackoverflow.com/questions/28552274/cartesian-product-of-a-list-of-sets-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!