简体   繁体   中英

Python Program that return sublists of a list

Please I want to design a function that return all possible subset of a list. Here is the code I tried

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

If what you're looking for is the powerset, itertools' recipe page has a nice, concise, memory-safe way to do that:

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))

Worth pointing out that finding a powerset is exponential O(2^n). Also, this question had been previously answered here .

Just using iterative method for doing this as i looped from 0 to 2^(length of list) and select each element based on the value of the loop counter

That is if the loop counter is 5 we select the first and third element

as 5 in binary is represented as 101 the we select the index elements with 1 in binary likewise for 7 we need first three elements 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]))

OUTPUT

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

also you might want convert this function to a generator as the returned list will be huge if the inputlist contains large number of values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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