Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating lists depending on sign changes

Tags:

python

I have excel Data (float) in one column where 20 changes of sings occur in every couple of hundred lines. The list is a couple of thousand lines long but simplyfied it looks like this [5, 4, 3, 2, 1, -5, -4, -3, -2, -1, 5, 4, 3, 2, 1, -5, ...].

I need lists containing all numbers to the point where a sign change occurs and then start a new list until the next sign change. So in total I want as many lists returned as there a sign changes. I need those to do numerical integration. I can do that though...

Can you give me an example with a short array like the one above? I don't really care if it gives the resluts as the return in a function or defines new variables. Whatever is easier or more elegant.

Thanks for the help guys.

like image 792
Alexander K Avatar asked Feb 02 '26 10:02

Alexander K


1 Answers

Assuming you want to group by sign, you can use itertools.groupby:

from itertools import groupby

data = [5, 4, 3, 2, 1, -5, -4, -3, -2, -1, 5, 4, 3, 2, 1, -5]


def groupby_sign(lst):
    return [list(group) for _, group in groupby(lst, key=lambda x: x < 0)]

result = groupby_sign(data)
print(result)

Output

[[5, 4, 3, 2, 1], [-5, -4, -3, -2, -1], [5, 4, 3, 2, 1], [-5]]
like image 140
Dani Mesejo Avatar answered Feb 05 '26 01:02

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!