Search code examples
pythonlistlist-manipulation

How to create sublists using a sentinel value?


I have python list that contains at least 990 elements (pressure values, numbers) e.g.

lst = ['x','y','z','g','h',1600000,'c','y','n','h','j','y', 1600000]

Turning points are marked by the sentinel value 1600000, and can occur anywhere in the list. I am trying to come up with sublists that contain numbers between 1600000. Since there is no fixed interval, indexing is not going to work.

For example, from lst, I want to create:

[['x','y','z','g','h'],['c','y','n','h','j','y']]

Can I get a hint regarding this?


Solution

  • Create two lists and append values to one and once the turning point appears, append that list to the other list:

    def split_list_at_n(lst,n):
        temp = []
        output = []
        if lst[-1] != n:
            lst.append(n)
        for x in lst:
            if x==n:
                output.append(temp)
                temp = []
            else:
                temp.append(x)
        return output
    
    split_list_at_n(lst, 1600000)
    

    Output:

    [['x', 'y', 'z', 'g', 'h'], ['c', 'y', 'n', 'h', 'j', 'y']]
    

    Unlike, finding the indices of turning points first, this iterates through the list only once.