删除仅在列表开头出现的0

时间:2014-07-28 15:20:29

标签: python list

我有一个列表,在我想要删除的开头有0。 0确实发生在数据的其他地方,但我想保留这些。

l=[0, 0, 0, 0, 151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

需要成为:

l=[151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

2 个答案:

答案 0 :(得分:9)

使用itertools.dropwhile()删除这些零:

from itertools import dropwhile
import operator

l = list(dropwhile(operator.not_, l))

这将删除 的初始0值;或者更确切地说,所有false-y值,使用operator.not_()

演示:

>>> from itertools import dropwhile
>>> import operator
>>> l=[0, 0, 0, 0, 151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]
>>> list(dropwhile(operator.not_, l))
[151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

答案 1 :(得分:1)

您可以使用方法list.index()和next():

L=[0, 0, 1, 2, 'a', 3, 0, 0, 9]

noLeadingZeros = L[L.index(next(i for i in L if i!=0)):]