Extracting lists from tuple with a condition

Question:

I’ve been trying to extracting from this tuples
E=tuple([random.randint(0,10) for x in range(10)])
Let’s say the result is (3,4,5,0,0,3,4,2,2,4) .

I want to extract from this tuple lists of numbers is ascending order without sorting the tuple or anything.
Example : [[3,4,5],[0,0,3,4],[2,2,4]]

Asked By: BouhaaCode

||

Answers:

You can create a custom function (generator in my example) to group ascending elements:

def get_ascending(itr):
    lst = []
    for v in itr:
        if not lst:
            lst = [v]
        elif v < lst[-1]:
            yield lst
            lst = [v]
        else:
            lst.append(v)
    yield lst


E = 3, 4, 5, 0, 0, 3, 4, 2, 2, 4
print(list(get_ascending(E)))

Prints:

[[3, 4, 5], [0, 0, 3, 4], [2, 2, 4]]
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.