Find monotonic sequences in a list?

后端 未结 4 410
一整个雨季
一整个雨季 2020-12-11 23:52

I\'m new in Python but basically I want to create sub-groups of element from the list with a double loop, therefore I gonna compare the first element with the next to figure

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 00:12

    I used a double loop as well, but put the inner loop in a function:

    #!/usr/bin/env python
    
    def process(lst):
    
        def prefix(lst):
            pre = []
            while lst and (not pre or pre[-1] <= lst[0]):
                pre.append(lst[0])
                lst = lst[1:]
            return pre, lst
    
        res=[]
        while lst:
            subres, lst = prefix(lst)
            res.append(subres) 
        return res
    
    print process([45,78,120,47,58,50,32,34])
    => [[45, 78, 120], [47, 58], [50], [32, 34]]
    

    The prefix function basically splits a list into 2; the first part is composed of the first ascending numbers, the second is the rest that still needs to be processed (or the empty list, if we are done).

    The main function then simply assembles the first parts in a result lists, and hands the rest back to the inner function.

    I'm not sure about the single value 50; in your example it's not in a sublist, but in mine it is. If it is a requirement, then change

            res.append(subres) 
    

    to

            res.append(subres[0] if len(subres)==1 else subres)
    
    print process([45,78,120,47,58,50,32,34])
    => [[45, 78, 120], [47, 58], 50, [32, 34]]
    

提交回复
热议问题