Home > Software design >  How to split a list into sublists based on single elements of the initial list first and then contig
How to split a list into sublists based on single elements of the initial list first and then contig

Time:12-18

I have been searching how to do this for the past while but can't seem to find anything that answers my problem or its idea and code is too complex for me to understand as a complete beginner. So basically this is the task I have to do:

Write a function all sublists(lst) that for a list lst returns as its result a list of all of sublists of lst. A sublist is a list containing a contiguous portion of the original i.e. comprising zero or more consecutive elements from the orginal.

For example, for the list [1, 2, 3] the result should be

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

What I started off doing was creating a whole list containing all of the numbers and then split it. However I can't use the split function since its a string and don't know any proper ways to splice it properly.

CodePudding user response:

use itertools.combinations

from itertools import combinations

l = [1, 2, 3]
final = []
for i in range(len(l) 1):
  final  = list(combinations(l,i))

print(final)

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

CodePudding user response:

Here is a function that finds your desired outcome using a double-loop:

def get_contiguous_sublists(lst):
    out = [[]]
    len_lst = len(lst)   1
    for length in range(1, len_lst):
        for i in range(len_lst - length):
            out  = [lst[i : i   length]]
    return out

Output:

>>> get_contiguous_sublists([1,2,3])
[[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]


>>> get_contiguous_sublists([1,2,3,4])
[[], [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4], [1, 2, 3, 4]]
  • Related