找到将列表决定为三的所有方法

问题描述 投票:1回答:2

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

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

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

python python-3.x list combinations
2个回答
2
投票

您可以使用库combinations中的itertools

import itertools

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个列表),瞧!您得到了结果


0
投票

这里是可能的解决方案:

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.append([])

# list2 is all combinations of sublists having length = length_of_a from the list1
list2 = list(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)]
results.append(a)

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

输出:

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

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

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

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

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

[1、2、3]

© www.soinside.com 2019 - 2024. All rights reserved.