Optymalne dzielenie listy względem elementu

1

Hej, w trakcie programu muszę podzielić listę względem zer tzn. mając wejście: *[0, -1, 0, 1, 0, 1, 2, 1, 2, 1, 2, 0] * otrzymuję wyjście: list([0, -1, 0], [0, 1, 0], [0, 1, 2, 1, 2, 1, 2, 0])
Napisałam taką pętlę, która działa, jednak dla dużej listy trwa to dosyć długo, jednak nie wiem, jak to zoptymalizować.

summary = [0, -1, 0, 1, 0, 1, 2, 1, 2, 1, 2, 0] 
cycles = []
get_cycles = summary.copy()

while get_cycles.count(0) > 1:
    first_zero_index = get_cycles.index(0)
    second_zero_index = get_cycles[first_zero_index + 1:].index(0) + first_zero_index + 1
    cycle = get_cycles[first_zero_index:second_zero_index + 1]
    cycles.append(cycle)
    get_cycles = get_cycles[second_zero_index:]

print(cycles)

Będę wdzięczna za każdą radę :)

3
summary = [0, -1, 0, 1, 0, 1, 2, 1, 2, 1, 2, 0]

def create(input_list:list = None) -> list:
    input_list = list(input_list)
    zeros = [x for x in range(len(input_list)) if input_list[x] == 0]
    new_list = [input_list[zeros[y]:zeros[y+1]+1] for y in range(len(zeros)-1)]
    return new_list

print(create(input_list=summary))

<<<< [[0, -1, 0], [0, 1, 0], [0, 1, 2, 1, 2, 1, 2, 0]]
3

Moje rozwiązanie jest brzydsze, ale zazwyczaj nieco szybsze, niestety nie zawsze, zależy od danych :)
Wrzucam moją wersję i porównanie

# summary = [0, -1, 0, 1, 0, 1, 2, 1, 2, 1, 2, 0] 
from random import randint
import time

summary = []
for i in range(5000000):
    summary.append(randint(-1,1))

start = time.time()
def create(input:list = None) -> list:
    zeros = [x for x in range(len(summary)) if summary[x] == 0]
    new_list = [summary[zeros[y]:zeros[y+1]+1] for y in range(len(zeros)-1)]
    return new_list
cycles1 = create(input=summary)
end = time.time()
print(end - start)

start = time.time()
cycles2 = []
pos1 = 0
pos2 = 0
try:
    while True:
        pos1 = summary.index(0, pos1)
        pos2 = summary.index(0, pos1+1)
        cycles2.append(summary[pos1:pos2+1])
        pos1 = pos2
except:
    pass
end = time.time()
print(end - start)

print(cycles1 == cycles2)

# print(cycles)

1 użytkowników online, w tym zalogowanych: 0, gości: 1