通过重复选择构造元组

2024-09-30 14:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个带有计数元组列表的输入数组,例如

r, s = 0.5, 2.0   # floats, given, guaranteed nonzero, guaranteed nonequal

[
    ((+r, -r), 2),
    ((+s, -s), 1),
    ((0,), 2),
    # ...
]

我想构建一个所有组合的列表,其中包含两个(+r, -r)(可能都是+r)、一个(+s, -s)和两个0,即

(+r, 0, -s, +r, 0),
(0, 0, -r, +r, +s),
...

可以有任意数量的元组。顺序不重要

有没有办法通过itertools实现这一点


Tags: 列表数量顺序数组given计数元组itertools
1条回答
网友
1楼 · 发布于 2024-09-30 14:22:18

我希望我正确理解了你的问题:

from itertools import combinations_with_replacement, product, chain, permutations

r, s = 0.5, 2.0
l = ((+r, -r), 2), ((+s, -s), 1), ((0,), 2)

seen = set()
for p in product(*[list(combinations_with_replacement(v, cnt)) for v, cnt in l]):
    for c in permutations(chain.from_iterable(p), sum(cnt for _, cnt in l)):
        if c not in seen:
            print(c)
            seen.add(c)

印刷品:

(0.5, 0.5, 2.0, 0, 0)
(0.5, 0.5, 0, 2.0, 0)
(0.5, 0.5, 0, 0, 2.0)
(0.5, 2.0, 0.5, 0, 0)
(0.5, 2.0, 0, 0.5, 0)
(0.5, 2.0, 0, 0, 0.5)
(0.5, 0, 0.5, 2.0, 0)
(0.5, 0, 0.5, 0, 2.0)
(0.5, 0, 2.0, 0.5, 0)
(0.5, 0, 2.0, 0, 0.5)
(0.5, 0, 0, 0.5, 2.0)
(0.5, 0, 0, 2.0, 0.5)

...

(0, -2.0, -0.5, 0, -0.5)
(0, -2.0, 0, -0.5, -0.5)
(0, 0, -0.5, -0.5, -2.0)
(0, 0, -0.5, -2.0, -0.5)
(0, 0, -2.0, -0.5, -0.5)

相关问题 更多 >