如何使用 python 迭代器生成多个变量的笛卡尔积?

发布于 2024-09-29 16:05:37 字数 410 浏览 2 评论 0原文

各位, 给定一个具有三个值的变量,我试图生成这些变量的三元组的所有可能组合。

虽然这段代码可以解决问题,但

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 问题:

  1. 我如何重写上面的代码使用迭代器?我的意思是,是否有可能有一个迭代器来生成上面“状态”的元素?

  2. 是否可以扩展它以不仅生成三元组,还可以生成 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:

  1. 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?

  2. Is it possible to extend this for generating not only triplets, but also 4-plets, 5-plets and so on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

双手揣兜 2024-10-06 16:05:37
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
淡莣 2024-10-06 16:05:37

使用itertools.product

>>> site_range=[0,1]
>>> list(product(site_range, repeat=3))
[000 001 010 011 100 101 110 111]

编辑 正如@Glenn Maynard 在评论中指出的那样,这不是笛卡尔积。为此,您必须检查 他的回答

Use itertools.product:

>>> site_range=[0,1]
>>> list(product(site_range, repeat=3))
[000 001 010 011 100 101 110 111]

Edit As @Glenn Maynard points out in a comment, this is not the cartesian product. For this, you will have to check his answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文