如何使用 python 迭代器生成多个变量的笛卡尔积?
各位, 给定一个具有三个值的变量,我试图生成这些变量的三元组的所有可能组合。
虽然这段代码可以解决问题,但
site_range=[0,1,2]
states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range]
它有点,嗯,笨拙,并且如果我尝试对三个以上变量的组合执行相同的操作,情况只会变得更糟
因此,我的 Python 101 问题:
我如何重写上面的代码使用迭代器?我的意思是,是否有可能有一个迭代器来生成上面“状态”的元素?
是否可以扩展它以不仅生成三元组,还可以生成 4-plet、5-plet 等?
Dear all,
Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables.
While this code does the trick,
site_range=[0,1,2]
states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range]
it's somewhat, uhm, clumsy, and is only getting worse if I try to do the same for combinations of more than three variables
Hence, my Python 101 questions:
How do I go about rewriting the code above using iterators? I mean, is it possible to have an iterator which would yield the elements of the "states" above?
Is it possible to extend this for generating not only triplets, but also 4-plets, 5-plets and so on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
itertools.product
:编辑 正如@Glenn Maynard 在评论中指出的那样,这不是笛卡尔积。为此,您必须检查 他的回答。
Use
itertools.product
:Edit As @Glenn Maynard points out in a comment, this is not the cartesian product. For this, you will have to check his answer.