Python 找出所有方法将列表分为三个部分
正如标题所说,我如何找到将一个列表划分为三个列表的所有方法?例如,1,2,3将返回Python 找出所有方法将列表分为三个部分,python,python-3.x,list,combinations,Python,Python 3.x,List,Combinations,正如标题所说,我如何找到将一个列表划分为三个列表的所有方法?例如,1,2,3将返回 [1, 2, 3] [1] [2] [3] [1, 2] [3] [ ] [1] [2, 3] [ ] [1, 3] [2] [ ] 我试过很多东西,但似乎都不懂。谢谢 您可以使用libitertools import itertools my_list = [1, 2, 3] for i in range(len(my_list)): print(list(itertools.combinatio
[1, 2, 3]
[1] [2] [3]
[1, 2] [3] [ ]
[1] [2, 3] [ ]
[1, 3] [2] [ ]
我试过很多东西,但似乎都不懂。谢谢 您可以使用lib
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), (2, 3)]
[(1, 2, 3)]
现在,您可以添加每个列表的长度,并添加缺少的空列表(以完成3个列表),瞧,您有了您的结果。下面是一个可能的解决方案:
import itertools
# your input data list
a = [1, 2, 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,2,..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]应该[1,2,3][]也是一个答案吗?@wkzhu应该是我的错,这回答了你的问题吗?