python中的集合列表的笛卡尔积 [英] Cartesian product of a list of sets in python
本文介绍了python中的集合列表的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一套餐具.我不知道列表的长度.我想用我正在编写的一些代码在列表中找到集合的笛卡尔积.
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.
例如: 我有
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')
如果我事先知道列表的大小为3,则可以使用以下代码生成该笛卡尔积.
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?
推荐答案
使用itertools.product(*list_of_sets)
.
这篇关于python中的集合列表的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文