diegoaguilar
diegoaguilar

Reputation: 8376

How to obtain sliced sublists of a list dynamically in python?

Let's say I have a list:

l = [0,1,2,3,4]

And I want to obtain a sequence of lists in this logic:

[[1,2,3,4],[0,1,2,3],[2,3,4],[1,2,3],[0,1,2],[3,4],[2,3],[1,2],[0,1],[0],[1],[2],[3],[4]]

That's it, sublists made of l[1:] and l[:-1]

I started by this recursive function:

l = [0,1,2,3,4]

def sublist(l):

    if len(l) == 1:
        return l
    else:
        return [sublist(l[1:]),sublist(l[:-1])]

a = [sublist(l)]

print a

But it's not really what I what as it outputs:

[[[[[[4], [3]], [[3], [2]]], [[[3], [2]], [[2], [1]]]], [[[[3], [2]], [[2], [1]]], [[[2], [1]], [[1], [0]]]]]]

Upvotes: 0

Views: 145

Answers (4)

Graeme Stuart
Graeme Stuart

Reputation: 6063

A simple recursion, doesn't quite order things correctly but its simple.

def sublists(l):
    right = l[1:]
    left = l[:-1]
    result = [right, left]
    if len(l) > 2:
        result.extend(sublists(right))
        result.extend(sublists(left))
    return result

print sublists([0,1,2,3,4])

Upvotes: 1

Markku K.
Markku K.

Reputation: 3908

Here's a very straightforward implementation:

def sublists_n(l, n):
    subs = []
    for i in range(len(l)-n+1):
        subs.extend([l[i:i+n]])
    return subs

def sublists(l):
    subs = []
    for i in range(len(l)-1,0,-1):
        subs.extend(sublists_n(l,i))
    return subs

>>> l = [0,1,2,3,4]
>>> sublists(l)
[[0, 1, 2, 3], [1, 2, 3, 4], [0, 1, 2], [1, 2, 3], [2, 3, 4], [0, 1], [1, 2], [2, 3], [3, 4], [0], [1], [2], [3], [4]]

Upvotes: 1

Ben
Ben

Reputation: 2472

import itertools
[list(itertools.combinations(l, x)) for x in range(1, len(l))]

Upvotes: 4

a p
a p

Reputation: 3208

[l[x:] for x in range(len(l))] + [l[:x+1] for x in range(len(l))]

Loops through l twice, but you sort of have to no matter what I think (could use zip but same thing).

Upvotes: 1

Related Questions