我想从数组中生成组合(总是4个元素):
arr = ["1","2","3","4"]
我目前正在使用:
itertools.combinations(arr, 2)
这会让我回复:
("1","2"),("1","3"),("1","4"),("2","3"),("2","4"),("3","4")
我想做的是仅生成依赖组合:
[("1","2"),("3","4")]
[("1","3"),("2","4")]
[("1","4"),("2","3")]
意思是如果我有字符串"1"
和"2"
的组合,则只剩下其他组合"3"
和"4"
。我当前的解决方案仅使用itertools
,因为每次计算都进行了两次("1","2"
对"3","4"
一次(因此在这种情况下,对"3","4"
是单独计算的;迭代在arr
上再次遗漏"1"
和"2"
),另一次"3","4"
与"1","2"
配对。
我相信应该有更优雅的方法来解决这个问题。
答案 0 :(得分:3)
为了好玩,这里有一个适用于任意数量偶数元素的解决方案,假设您希望每个依赖组合分成两个偶数组:
from itertools import combinations
arr = [1, 2, 3, 4, 5, 6]
group_size = len(arr) // 2
tuples = list(combinations(arr, group_size))
dependent_combinations = [
[tuples[i], tuples[-i-1]]
for i in range(len(tuples) // 2)
]
print(dependent_combinations)
输出:
[
[(1, 2, 3), (4, 5, 6)],
[(1, 2, 4), (3, 5, 6)],
[(1, 2, 5), (3, 4, 6)],
[(1, 2, 6), (3, 4, 5)],
[(1, 3, 4), (2, 5, 6)],
[(1, 3, 5), (2, 4, 6)],
[(1, 3, 6), (2, 4, 5)],
[(1, 4, 5), (2, 3, 6)],
[(1, 4, 6), (2, 3, 5)],
[(1, 5, 6), (2, 3, 4)]
]
答案 1 :(得分:2)
如果数组总是包含4个元素(如您所述),则可以轻松构建所有选项:
arr = ["1","2","3","4"]
for i in range(1,4):
print([arr[0], arr[i]], arr[1:i] + arr[i+1:])
#output:
['1', '2'] ['3', '4']
['1', '3'] ['2', '4']
['1', '4'] ['2', '3']