繁体   English   中英

查找所有组合以将单个列表拆分为两个列表

[英]Find all combinations to split a single list into two lists

我有一个包含少量元素的列表,我想找到将这个列表分成两个列表的所有可能性。

我的意思是,所有组合都意味着我不会关心它的元素顺序。 即如果元素 2 和 3 在一个列表中,则元素 1 在另一个列表中。 ([2,3],[1]) == ([1],[2,3])

这是我尝试过的:

import itertools

input_list = [10, 5, 15, 20, 25]
subset1, subset2, subsets = [], [], []


#sort input list
stuff = list(input_list)
stuff.sort()

#Find all possible [0] positions of given list
for L in range(0, len(stuff)+1):
    for subset in itertools.permutations(stuff, L):
        temp1 = list(subset)
        temp1.sort()
        if temp1 not in subset1:
            subset1.append(list(temp1))

#find all possible [1] positions 
for L2 in range(len(subset1)):
    temp2 = list( set(stuff) - set(subset1[L2]))
    temp2.sort()
    subset2.append(temp2)

#combine two position lists and filter out same combination  
for L3 in range(len(subset1)):
    temp3 = [subset1[L3],subset2[L3]]

    temp3.sort()

    #filter out same combination result but different order
    if temp3 not in subsets:
        subsets.append(temp3)

当我运行这段代码时,我发现我的子集列表的元素很少包含意外的元组数据,比如 [[5, 25], [10, 15, 20], ([5, 15, 25], [10, 20 ])]。

我完全混淆了这些元组类型数据的来源。 有人能指出我错过了什么吗?

谢谢

当我执行你的代码时,我得到 output

[[[], [5, 10, 15, 20, 25]], [[5], [10, 15, 20, 25]], [[5, 15, 20, 25], [10]], [[5, 10, 20, 25], [15]], [[5, 10, 15, 25], [20]], [[5, 10, 15, 20], [25]], [[ 5, 10], [15, 20, 25]], [[5, 15], [10, 20, 25]], [[5, 20], [10, 15, 25]], [[5, 25], [10, 15, 20]], [[5, 20, 25], [10, 15]], [[5, 15, 25], [10, 20]], [[5, 15, 20], [10, 25]], [[5, 10, 25], [15, 20]], [[5, 10, 20], [15, 25]], [[5, 10, 15] , [20, 25]]]

里面没有任何元组。 使用 itertools 的一种更简单的解决方案可能是

def two_partitions(S):
    res_list = []
    for l in range(0,int(len(S)/2)+1):
        combis = set(itertools.combinations(S,l))
        for c in combis:
            res_list.append((sorted(list(c)), sorted(list(S-set(c)))))
    return res_list

two_partitions({10, 5, 15, 20, 25})

您可能需要也可能不需要子列表的排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM