2017-09-22 49 views
3

我想删除列表中最初出现的零的列表,但它的行为很奇怪,我试过的方法。从python的列表中删除第一个发生的零

a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0] 

for i in a: 
    if i == 0: a.remove(i) 
    else: pass 

print (a) 

>>> [0, 3, 4, 0, 6, 0, 14, 16, 18, 0] 

但我需要这样

[3,4,0,6,0,14,16,18,0]

的输出和也可以让假设列表增长或减少,所以我不能保持零的范围并删除它们。我哪里错了。

+1

不要修改列表,而你迭代他们或哟你会得到意想不到的结果。 – skrx

回答

5

你的循环跳过项目。你删除一个,然后迭代到下一个位置。

只要找到第一个非零的位置,并修剪列表

a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0] 

i = 0 
while a[i] == 0: 
    i+=1 

print(a[i:]) # [3, 4, 0, 6, 0, 14, 16, 18, 0] 
2
def removeLeadingZeros(a): 
    for l in a: 
     if l == 0: 
      a = a[1:] 
     else: 
      break 
    return a 

,或者如果你想把它当作使用numpy的数组a oneliner:

a = list(a[np.where(np.array(a) != 0)[0][0]:]) # you could remove the list() if you don't mind using numpy arrays 
1

itertools.dropwhile下降可迭代的元素,只要谓词为真:

from itertools import dropwhile 

a = list(dropwhile(lambda x: x==0, a)) 
2

略有不同,那么答案已经给出,所以在这里:

a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0] 

for i in range(0, len(a)): 
    if a[i] != 0: 
     a = a[i:] 
     break 

print (a)