python中三个集合之间的置换

2024-10-03 17:24:25 发布

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

我有三套

A = {'a', 'b', 'c'}
B = {'1', '2'}
C = {'d', 'e', 'f'}

现在我想要的是python中的如下内容:

{'a1d', 'b1e', 'c1f'}
{'a1e', 'b1f', 'c1d'}
.
.
.
{'a2e', 'b2f', 'c2d'}

在不干扰集合A的情况下所有这些可能的组合

不允许重复集合C中的元素。你知道吗

例如{'a2e', 'b2e', 'c2d'}是不允许的。你知道吗


Tags: 元素内容情况a1db1fc2da1eb1e
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:25

实际上是在集合B上循环,用A压缩C的排列:

from itertools import permutations

for b in B:
    for cperm in permutations(C):
        res = {''.join([a, b, c]) for a, c in zip(A, cperm)}
        print res

输出:

>>> from itertools import permutations
>>> A = {'a', 'b', 'c'}
>>> B = {'1', '2'}
>>> C = {'d', 'e', 'f'}
>>> for b in B:
...     for cperm in permutations(C):
...         res = {''.join([a, b, c]) for a, c in zip(A, cperm)}
...         print res
... 
set(['a1e', 'b1f', 'c1d'])
set(['a1e', 'b1d', 'c1f'])
set(['b1f', 'a1d', 'c1e'])
set(['a1d', 'b1e', 'c1f'])
set(['b1d', 'a1f', 'c1e'])
set(['b1e', 'a1f', 'c1d'])
set(['b2f', 'a2e', 'c2d'])
set(['b2d', 'c2f', 'a2e'])
set(['b2f', 'a2d', 'c2e'])
set(['c2f', 'b2e', 'a2d'])
set(['b2d', 'a2f', 'c2e'])
set(['b2e', 'c2d', 'a2f'])

其中,集合是无序的,因此每个集合的顺序与输出示例不同。你知道吗

添加一些排序:

>>> for b in B:
...     for cperm in permutations(C):
...         res = {''.join([a, b, c]) for a, c in zip(A, cperm)}
...         print '{{{0!r}, {1!r}, {2!r}}}'.format(*sorted(res))
... 
{'a1e', 'b1f', 'c1d'}
{'a1e', 'b1d', 'c1f'}
{'a1d', 'b1f', 'c1e'}
{'a1d', 'b1e', 'c1f'}
{'a1f', 'b1d', 'c1e'}
{'a1f', 'b1e', 'c1d'}
{'a2e', 'b2f', 'c2d'}
{'a2e', 'b2d', 'c2f'}
{'a2d', 'b2f', 'c2e'}
{'a2d', 'b2e', 'c2f'}
{'a2f', 'b2d', 'c2e'}
{'a2f', 'b2e', 'c2d'}

通过将B集合加倍到2个列表中并在每个排列中仅选取3个元素,可以实现跨B产生重复一个数字的排列:

for bperm in permutations(list(B) * 2, r=3):
    for cperm in permutations(C):
        res = {''.join([a, b, c]) for a, b, c in zip(A, bperm, cperm)}

相关问题 更多 >