How to create sublists using a sentinel value?

111 Views Asked by At

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?

3

There are 3 best solutions below

0
AudioBubble On BEST ANSWER

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.

1
Dan C. Vo On

Looks like you're trying to extract elements between the 160000s.

As a suggestion, you should first count() the 160000 (or whatever you use for turning points) to ensure that you have exactly two turning points within the given list. Otherwise, you should handle the cases differently with different numbers of turning points in your given list. When you have exactly two 160000, use find() to find out the indexes of these two points. Eventually, you can just get the sublist of the given list within the range of [ firstTurningPointIndex, secondTurningPointIndex ]

1
Agent Biscutt On

So, I would start by first working out how to iterate through the list, and then working out how to append to the appropriate sublist.

So, the you would need to figure out how to stop putting the variables in each sublist and move onto the next sublist when the turning point is reached.

And also, working out some if's and else's to stop the turning point from turning up in your data (if thats what you want).

Finally, just return the variable, and check whether the result was what you wanted. If not try again.

I have come up with one solution for this:

def split_list(l,n):
  rl=[[]]
  c=0
  for x in l:
    if x!=n:
      rl[c].append(x)
    else:
      rl.append([])
      c+=1
  return(rl)

This returns all sublists for each interval (space separated by 1600000). I have made it so that you can enter any practical value and it will return sublists based off that value.

Use it like this:

a=split_list(li,1600000)