Home > Net >  Extracting lists from tuple with a condition
Extracting lists from tuple with a condition

Time:11-10

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

CodePudding user response:

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]]
  • Related