简体   繁体   English

我将如何删除此 python 列表中 1 之前的所有零

[英]How would I remove all the zeros before the 1 in this python list

result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]

I want this list to be turned into我想把这个列表变成

result = [1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]

I have tried using a while loop to keep removing zeros until it finds a 1 but I cant seem to get that to work.我曾尝试使用 while 循环不断删除零,直到找到 1,但我似乎无法使其正常工作。

for x in result:
    while (x == 0):
        result.remove(0)

If there always is a 1, you could just find it and delete everything before it:如果总是有一个 1,你可以找到它并删除它之前的所有内容:

del result[:result.index(1)]

Or if it could be all zeros:或者,如果它可以全为零:

if any(result):
    del result[:result.index(1)]

or或者

try:
    del result[:result.index(1)]
except ValueError:
    pass

or或者

result.append(1)
del result[:result.index(1)]
result.pop()

One way using itertools.dropwhile :使用itertools.dropwhile一种方法:

from itertools import dropwhile

list(dropwhile(lambda x: x == 0, result))

Output:输出:

[1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]

Problem in your code is you are changing the list while iterating.您的代码中的问题是您在迭代时更改了列表。 Instead you can use while loop.相反,您可以使用 while 循环。

while result and result[0] == 0:
    result.pop(0)
print(result)

Output:输出:

[1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]

Or else try the following :或者尝试以下操作:

result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]
a=''
for i in result:
    a=a+str(i)
print(list(a.lstrip('0')))
result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]

# prints index of 1st (leftmost) '1' encountered in the list
# print(result.index(1)) 

# print from that index to the wholw remaining list
print(result[result.index(1):])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM