【问题标题】:Find all combinations to split a single list into two lists查找所有组合以将单个列表拆分为两个列表
【发布时间】:2019-11-18 06:18:45
【问题描述】:

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

我的意思是,所有组合都意味着我不会关心它的元素顺序。 即如果元素 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)

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

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

谢谢

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    当我执行你的代码时,我得到了输出

    [[[], [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})
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 2011-11-16
      • 2010-09-27
      相关资源
      最近更新 更多