using itertools to generate the Cartesian product of list of lists

萝らか妹 提交于 2019-12-13 05:10:05

问题


I'm trying to solve the problem mentioned in this post. Consider the D=[d1,...,dm] a list of non-negative integers. I want to have the set of the Cartesian products of range(d1),...,range(dm). For example if m=3 I could use 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.


回答1:


You can use map to map all items of D to range and then unpack them for product:

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



回答2:


You can use * for this:

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


来源:https://stackoverflow.com/questions/51636305/using-itertools-to-generate-the-cartesian-product-of-list-of-lists

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