简体   繁体   English

使用itertools生成列表列表的笛卡尔积

[英]using itertools to generate the Cartesian product of list of lists

I'm trying to solve the problem mentioned in this post . 我试图解决中提到的问题这篇文章 Consider the D=[d1,...,dm] a list of non-negative integers. 考虑D=[d1,...,dm]非负整数的列表。 I want to have the set of the Cartesian products of range(d1),...,range(dm) . 我想要一组range(d1),...,range(dm)的笛卡尔积。 For example if m=3 I could use itertools: 例如,如果m=3我可以使用itertools:

 indices=[i for i in itertools.product(range(d1),range(d2),range(d3))]

I would appreciate if you could help me know how I can generate the indices using D with arbitrary length. 如果您能帮助我知道如何使用任意长度的D生成indices将不胜感激。

您可以使用mapD所有项目映射到range ,然后将它们解压为product

indices=list(itertools.product(*map(range, D)))

您可以使用*

[i for i in itertools.product(*map(range, D))]

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

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