从 Python 中的列表中查找唯一的三胞胎
Finding unique triplets from list in Python
我正在 python 中编写一些研究脚本,我有一个包含 9 个元素的列表:
a = [1,2,3,4,5,6,7,8,9]
我想找到包含 3 个元素(而不是 3 个元素集本身)的子集的所有组合,例如:
a_new = [ [ [1,2,3],[4,5,6],[7,8,9] ] ],
[ [2,3,4],[5,6,7],[8,9,1] ],
[ [3,4,6],[1,2,8],[5,7,9] ], etc.... ]
- 元素在子集中不重复
- 集合 [3,2,1] 和 [1,2,3] 是同一集合并且不唯一
您是否遇到过这种情况,或者某些 Python 图书馆会处理它?
问候
你可以使用itertools
内置模块
from itertools import combinations
a = [1,2,3,4,5,6,7,8,9]
combination = list(combinations(a, 3))
此输出为元组,您可以轻松转换为列表。
from itertools import combinations
a = {1, 2, 3, 4, 5, 6, 7, 8, 9}
# pick 3
for c_out in combinations(a, r=3):
s_out = set(c_out)
# pick the next 3 from the those elements that are not already picked (i.e not in s_out)
for c_in in combinations(a - s_out, r=3):
# there only 3 elements left so only one way to pick
rest = tuple(a - (s_out | set(c_in)))
print(c_out, c_in, rest)
输出 (部分)
(1, 2, 3) (4, 5, 6) (8, 9, 7)
(1, 2, 3) (4, 5, 7) (8, 9, 6)
(1, 2, 3) (4, 5, 8) (9, 6, 7)
(1, 2, 3) (4, 5, 9) (8, 6, 7)
(1, 2, 3) (4, 6, 7) (8, 9, 5)
(1, 2, 3) (4, 6, 8) (9, 5, 7)
(1, 2, 3) (4, 6, 9) (8, 5, 7)
(1, 2, 3) (4, 7, 8) (9, 5, 6)
(1, 2, 3) (4, 7, 9) (8, 5, 6)
(1, 2, 3) (4, 8, 9) (5, 6, 7)
(1, 2, 3) (5, 6, 7) (8, 9, 4)
(1, 2, 3) (5, 6, 8) (9, 4, 7)
(1, 2, 3) (5, 6, 9) (8, 4, 7)
(1, 2, 3) (5, 7, 8) (9, 4, 6)
您可以在 documentation.
中阅读更多关于集合操作(并集、差集)的信息
我正在 python 中编写一些研究脚本,我有一个包含 9 个元素的列表:
a = [1,2,3,4,5,6,7,8,9]
我想找到包含 3 个元素(而不是 3 个元素集本身)的子集的所有组合,例如:
a_new = [ [ [1,2,3],[4,5,6],[7,8,9] ] ],
[ [2,3,4],[5,6,7],[8,9,1] ],
[ [3,4,6],[1,2,8],[5,7,9] ], etc.... ]
- 元素在子集中不重复
- 集合 [3,2,1] 和 [1,2,3] 是同一集合并且不唯一
您是否遇到过这种情况,或者某些 Python 图书馆会处理它?
问候
你可以使用itertools
内置模块
from itertools import combinations
a = [1,2,3,4,5,6,7,8,9]
combination = list(combinations(a, 3))
此输出为元组,您可以轻松转换为列表。
from itertools import combinations
a = {1, 2, 3, 4, 5, 6, 7, 8, 9}
# pick 3
for c_out in combinations(a, r=3):
s_out = set(c_out)
# pick the next 3 from the those elements that are not already picked (i.e not in s_out)
for c_in in combinations(a - s_out, r=3):
# there only 3 elements left so only one way to pick
rest = tuple(a - (s_out | set(c_in)))
print(c_out, c_in, rest)
输出 (部分)
(1, 2, 3) (4, 5, 6) (8, 9, 7)
(1, 2, 3) (4, 5, 7) (8, 9, 6)
(1, 2, 3) (4, 5, 8) (9, 6, 7)
(1, 2, 3) (4, 5, 9) (8, 6, 7)
(1, 2, 3) (4, 6, 7) (8, 9, 5)
(1, 2, 3) (4, 6, 8) (9, 5, 7)
(1, 2, 3) (4, 6, 9) (8, 5, 7)
(1, 2, 3) (4, 7, 8) (9, 5, 6)
(1, 2, 3) (4, 7, 9) (8, 5, 6)
(1, 2, 3) (4, 8, 9) (5, 6, 7)
(1, 2, 3) (5, 6, 7) (8, 9, 4)
(1, 2, 3) (5, 6, 8) (9, 4, 7)
(1, 2, 3) (5, 6, 9) (8, 4, 7)
(1, 2, 3) (5, 7, 8) (9, 4, 6)
您可以在 documentation.
中阅读更多关于集合操作(并集、差集)的信息