找到所有方法来决定列表成三

就像标题中所说的,如何找到将列表分为三个列表的所有方式?例如1,2,3将返回

[1,3]
[1] [2] [3]
[1,2] [3] [ ]
[1] [2,3] [ ]
[1,3] [2] [ ]

我尝试了很多东西,但似乎无法理解。谢谢!

huangyanglv 回答:找到所有方法来决定列表成三

您可以从库combinations中使用itertools

import itertools

my_list = [1,2,3]

for i in range(len(my_list)):
    print(list(itertools.combinations(my_list,i + 1)))

输出

[(1,),(2,(3,)]
[(1,2),(1,3),3)]
[(1,3)]

现在您可以添加每个列表的长度,并添加缺少的空列表(以完成3个列表),瞧-您得到的结果

,

这是一个可能的解决方案:

import itertools

# your input data list
a = [1,3]

# util function to convert list of tuples to list of list
f = lambda x: [list(i) if isinstance(i,tuple) else i for i in x]

# list1 is all combinations of sublists having length = 1,..length_of_a from input list `a` and empty list [] 
list1 = []
for i in range(1,len(a)+1):
    list1.extend(itertools.combinations(a,i))
list1.extend([()]*(len(a)-1))

# list2 is all combinations of sublists having length = length_of_a from the list1
list2 = list(set(itertools.combinations(list1,len(a))))

#  filtering out and converting list of tuples for the final results
results = [f(i) for i in list2 if sum(itertools.chain(*i)) == sum(a) and set(itertools.chain(*i)) == set(a)]
results.append(a)

# print out the results
for r in results:
    print(r)

输出:

[[1、2、3],[],[]]

[[3],[1、2],[]]

[[1],[2],[3]]

[[2],[1、3],[]]

[[1],[2、3],[]]

[1、2、3]

本文链接:https://www.f2er.com/3151174.html

大家都在问