Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of all possible nested sequences from another list

Tags:

python

 List1=[0, 1, 2, 3, 4, 5]

I'd like to produce the following list2 containing four-element nested sequences from list1.

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

The eventual problem will use list1 with more elements and list2 with more than four-element nested sequences. However, I believe the logic is the same and hope the example is clear.

I'm basically looking for all “x-element” progressive nested sequences possible from a given list1.

I've written a loop to produce list2 with three-element nested sequences. Unfortunately, my solution is ugly and the more elements in my nested sequences, the uglier it gets. My guess/hope is this is a known math problem with a simple Python solution. My research leads me to believe it's a recursion problem, but I'm having a difficult time translating it into code.

like image 913
user3180110 Avatar asked Dec 28 '25 15:12

user3180110


1 Answers

Look up itertools.combinations

Basically, what you are looking for is:

import itertools
itertools.combinations([0, 1, 2, 3, 4, 5], 4)
like image 109
inspectorG4dget Avatar answered Dec 30 '25 04:12

inspectorG4dget