查找每个数字选自不同集合的所有组合

发布于 2025-01-05 12:17:54 字数 209 浏览 1 评论 0原文

我需要生成数字序列的每种组合,其中每个数字都可以从有限集中选取。

例如:

(1|2)、(1|2)、(2|3)、(2|3)、(2|3)、(3|4|5)

其中第一位数字可以是 1 或2,最后一位数字可以是 3、4 或 5。1,2,2,3,2,4

是有效组合,但 3,2,2,3,2,4 则不是。

做到这一点最简单的方法是什么?

I need to generate every combination of a sequence of digits where each digit can be picked from a finite set.

For example:

(1|2), (1|2), (2|3), (2|3), (2|3), (3|4|5)

Where the first digit can be a 1 or a 2, and the last digit can be a 3, 4, or 5.

1,2,2,3,2,4 would be a valid combination, but 3,2,2,3,2,4 wouldn't.

What's the easiest way to do this?

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

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

发布评论

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

评论(1

狠疯拽 2025-01-12 12:17:54

itertools.product 正是这样做的:

import itertools

for x in itertools.product('12','12','23','23','23','345'):
    print(', '.join(x))

itertools.product does exactly that:

import itertools

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