Istnieje bardziej wydajne rozwiązanie niż wbudowany itertools.dropwhile()
. Możesz użyć wszechmocnego collections.deque
, który byłby idealną strukturą danych dla tego zadania, ponieważ jego lewy lub prawy pop
jest O(1)
. Oto przypadek lewy pas, a prawy pas będzie tylko lustrzanym odbiciem go:
from collections import deque
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)
l = [0, 0, 1, 1, 2, 2, 0]
print(noLeadingZero(l))
# Result:
# [1, 1, 2, 2, 0]
Przetestujmy swoje wyniki z poniższego kodu, który wykorzystuje wbudowany w itertools.dropwhile()
:
from itertools import dropwhile
print(list(dropwhile(lambda x: x == 0, l)))
Oto badanie skuteczności:
import timeit
print timeit.timeit(
setup= """from itertools import dropwhile
l = [0, 0, 1, 1, 2, 2, 0]""",
stmt="""list(dropwhile(lambda x: x == 0, l))""") #2.308
print timeit.timeit(
setup= """from collections import deque
l = [0, 0, 1, 1, 2, 2, 0]
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)""",
stmt="""noLeadingZero(l)""") #1.684 -> Win!
I dla rstrip (wariantu): 'odwrócone (itertools.dropwhile (N x: x == 0 odwróconych (L))) ' –
rstrip () wariant jest w rzeczywistości 'list (odwrócona (lista (itertools.dropwhile (lambda x: x == 0, odwrócona (L))))) – josch