Use python to split a list of values โ€‹โ€‹into two lists when a negative value occurs while looping

Let's say I have a list of floats. I was wondering how I would iterate over the list and whenever a negative value occurs, to split the list into two separate lists.

Initial set of values: [0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0, -0.8, -12.0, -8.2, -2.5, - 6.9, -1.3, 0.0]

Search Result I'm looking for:

listA = [0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0]

listB = [-0.8, -12.0, -8.2, -2.5, -6.9, -1.3, 0.0]

The key here will be that the length of the list will change, and the position at which the first negative value occurs will never be the same.

So, in short: wherever the first negative value occurs, split into two separate lists.

Any ideas? Any help would be greatly appreciated. -Cheers

+3


source to share


3 answers


First, you can use a generator expression to find the index of the first negative value:

neg = next((i for i, v in enumerate(values) if v < 0), -1)

      



Then draw your list (assuming neg != -1

):

listA, listB = values[:neg], values[neg:]

      

+5


source


The idea is very simple, looping over your list, if the number is positive, add it to the first list, if the number is negative, then rotate saw_negative = True

and from now on add to the second list.

li = [0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0, -0.8, -12.0, -8.2, -2.5, -6.9, -1.3, 0.0]
first_li = []
second_li = []
saw_negative = False
for item in li:
    if item >= 0 and not saw_negative:
        first_li.append(item)
    elif item < 0 or saw_negative:
        saw_negative = True
        second_li.append(item)
print first_li
print second_li

      

Output:

[0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0]
[-0.8, -12.0, -8.2, -2.5, -6.9, -1.3, 0.0]

      



This is another approach until a negative number adds the number to the first list, whenever the number is negative add the rest of the list to the second list and break the loop

li = [0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0, -0.8, -12.0, -8.2, -2.5, -6.9, 
-1.3, 0.0]
first_li = []
second_li = []
for index, item in enumerate(li):
    if item < 0:
        second_li = li[index:]
        break
    first_li.append(item)
print first_li
print second_li

      

Output:

[0.1, 0.5, 3.2, 8.2, 0.0, 19.7, 0.0]
[-0.8, -12.0, -8.2, -2.5, -6.9, -1.3, 0.0]

      



+1


source


This can also be done in a functional style using groupby

and chain

from the standard library module itertools

:

from itertools import groupby, chain

def split_at_first_negative(lst):
    """Split the list at the first occurrence of a negative value.

    >>> split_at_first_negative([1, 2, 3, -1, -5, -3, 5, -6, 1])
    ([1, 2, 3], [-1, -5, -3, 5, -6, 1])
    """
    groups = groupby(lst, lambda x: x >= 0)
    first = list(next(groups)[1])
    second = list(chain.from_iterable(g[1] for g in groups))
    return first, second

      

0


source







All Articles