【问题标题】:How would I remove all the zeros before the 1 in this python list我将如何删除此 python 列表中 1 之前的所有零
【发布时间】:2020-09-11 02:19:19
【问题描述】:
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]

我想把这个列表变成

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

我尝试使用 while 循环来不断删除零,直到找到 1,但我似乎无法让它工作。

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

【问题讨论】:

  • 总会有至少一个 1 吗?

标签: python list loops


【解决方案1】:

如果总是有一个 1,你可以找到它并删除它之前的所有内容:

del result[:result.index(1)]

或者如果它可能是全零:

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

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

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

【讨论】:

    【解决方案2】:

    一种使用itertools.dropwhile的方式:

    from itertools import dropwhile
    
    list(dropwhile(lambda x: x == 0, result))
    

    输出:

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

    【讨论】:

      【解决方案3】:

      您的代码中的问题是您在迭代时更改了列表。相反,您可以使用 while 循环。

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

      输出:

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

      【讨论】:

        【解决方案4】:

        或者尝试以下方法:

        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')))
        

        【讨论】:

          【解决方案5】:
          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):])
          

          【讨论】:

            猜你喜欢
            • 2019-12-09
            • 2019-06-19
            • 1970-01-01
            • 2012-07-28
            • 1970-01-01
            • 2021-12-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多