Python - 在列表中查找所有可能的元素分组

时间:2018-05-08 14:58:40

标签: python list grouping

我正在尝试找到一种不错的Pythonic方法来查找将列表拆分为两组的所有可能组合,如下例所示:

my_array = [A,B,C]

输出应为:

[[[A],[B]]
[[A],[B,C]]
[[A],[C]]
[[A,B],[C]]
[[A,C],[B]]
[[B],[A]]
[[B],[A,C]]
[[B],[C]]
[[B,C],[A]]
[[C],[A]]
[[C],[A,B]]
[[C],[B]]]

谢谢!

1 个答案:

答案 0 :(得分:1)

也许这就是你所需要的:

import itertools

my_array = ['A','B','C']

combos = []

for i in range(1,len(my_array)):
    combos += itertools.combinations(my_array, i)

result = []

for c1 in combos:
    curr = list(c1)
    for c2 in combos:
        if not any(i in curr for i in c2):
            result.append([curr, list(c2)])
result
#[[['A'], ['B']],
# [['A'], ['C']],
# [['A'], ['B', 'C']],
# [['B'], ['A']],
# [['B'], ['C']],
# [['B'], ['A', 'C']],
# [['C'], ['A']],
# [['C'], ['B']],
# [['C'], ['A', 'B']],
# [['A', 'B'], ['C']],
# [['A', 'C'], ['B']],
# [['B', 'C'], ['A']]]