Jake Schurch Jake Schurch - 3 months ago 16
Python Question

Subsetting python list into positive/negative movements/trends

Sorry for creating this question but I have been stuck on this question for a while.

Basically I'm trying to take a list:

numbers=[1, 2, -1, -2, 4, 5]


And subset this list into a list of list that display positive/negative movements (or trends)

The end result is to have:

subset_list = [[1, 2], [-1, -2], [4, 5]]


Basically I have been using nested while functions to append a positive movement to the subset, and when the condition is not met, the subset is appended to subset_list and then evaluates if there is a negative movement.

I keep getting an
IndexError
, and so far
subset_list
only contains
[[1, 2]]


Here is my code:

numbers = [1,2,-1,-2,4,5]

subset = []
subset_list = []
subset.append(numbers[0])

i = 1
while i < (len(numbers)):
if numbers[i] <= numbers[i+1]:
subset.append(numbers[i])
i+= 1
while subset[-1] <= numbers[i] or numbers[i] <= numbers[i+1]:
subset.append(numbers[i])
i += 1
subset_list.append(subset)
subset = []
i += 1
if numbers[i] > numbers[i+1]:
subset.append(numbers[i])
i+= 1
while subset[-1] <= numbers[i] or numbers[i] <= numbers[i+1]:
subset.append(numbers[i])
i+= 1
subset_list.append(subset)
subset = []
i += 1


Thanks!

-Jake

Answer

Here is a way to re-write this:


numbers=[1,2,-1,-2,4,5] 


direction = True  # positive or negative
prevdirection = True
res = [[numbers[0]]]

for previtem, item in zip(numbers[:-1], numbers[1:]):
    direction = True if item - previtem > 0 else False
    if direction != prevdirection:
        res.append([])
    prevdirection = direction
    res[-1].append(item)

print(res)