【问题标题】:Python Program that return sublists of a list返回列表的子列表的 Python 程序
【发布时间】:2018-02-14 16:59:20
【问题描述】:

我想设计一个返回列表所有可能子集的函数。这是我尝试过的代码

def mylist(list1):
    for I in list1:
        print(i)

【问题讨论】:

标签: python


【解决方案1】:

只是使用迭代方法来做到这一点 我从0 循环到2^(length of list) 并根据循环计数器的值选择每个元素

也就是说如果循环计数器是5我们选择第一个和第三个元素

由于二进制中的 5 表示为 101,我们选择二进制中为 1 的索引元素,同样对于 7,我们需要前三个元素 111

def mylist(list1):
    num=len(list1)
    result=[]
    for i in range(1<<num):
        temp=list()
        index=0
        while i:
            if i&1==1:
                temp.append(list1[index])
            index+=1;
            i>>=1
        result.append(temp)
    return result

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

输出

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

您也可能希望将此函数转换为生成器,因为如果输入列表包含大量值,则返回的列表将很大

【讨论】:

    【解决方案2】:

    如果您正在寻找的是 powerset,itertools' recipe page 有一个很好的、简洁的、内存安全的方法来做到这一点:

    from itertools import chain, combinations
    
    def powerset(iterable):
        """
        powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
        """
        s = list(iterable)
    
        # note that this returns an iterator rather than a list
        return chain.from_iterable(combinations(s,n) for n in range(len(s)+1))
    

    值得指出的是,找到幂集是指数 O(2^n)。另外,这个问题之前已经回答过here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      相关资源
      最近更新 更多