簡體   English   中英

返回列表子列表的 Python 程序

[英]Python Program that return sublists of a list

請我想設計一個返回列表的所有可能子集的函數。 這是我試過的代碼

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

如果您正在尋找的是 powerset,則itertools 的配方頁面有一個很好的、簡潔的、內存安全的方式來做到這一點:

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)。 另外,這個問題之前已經在這里回答

只需使用迭代方法來執行此操作,因為我從02^(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]]

您也可能希望將此函數轉換為生成器,因為如果輸入列表包含大量值,則返回的列表將很大

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM