使用itertools生成列表列表的笛卡尔积 [英] using itertools to generate the Cartesian product of list of lists

查看:58
本文介绍了使用itertools生成列表列表的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决这篇文章中提到的问题.考虑D=[d1,...,dm]非负整数列表.我想要一组range(d1),...,range(dm)的笛卡尔积.例如,如果m=3我可以使用itertools:

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))]

如果您能帮助我知道如何使用任意长度的D生成indices,我将不胜感激.

I would appreciate if you could help me know how I can generate the indices using D with arbitrary length.

推荐答案

您可以使用mapD的所有项目映射到range,然后将其解压缩为product:

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)))

这篇关于使用itertools生成列表列表的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆