【问题标题】:My loop keeps breaking after I hit the if statement as true [duplicate]在我将 if 语句设为 true [重复] 后,我的循环不断中断
【发布时间】:2019-06-30 01:04:59
【问题描述】:

我正在运行这段代码,但由于某种原因,当数组中有 2 个元素应该命中“if not inc”语句时,它只会弹出 1 个元素。

我使用打印进行调试,似乎循环在第一次“if not inc”== true 之后中断,我不希望这种情况发生。它应该继续循环并再次回到那里。

已经尝试通过并继续,仍然没有预期的结果

def readFile():
    with open('incidents.txt') as f:
        x = f.read().splitlines()
        print(x)

    i = 0
    for inc in x:
        print(i)
        if not inc:
            x.pop(i)
            print("if command")
            pass
        i = i + 1
        print(x)


    y = x
    return y

Original Array -
['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555', '', '']

Expected result is -
['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555']

Actual Result is -
['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555', '']

【问题讨论】:

  • 您是否要删除空元素?使用过滤器之类的东西。

标签: python loops if-statement break


【解决方案1】:

使用像i 这样的计数器变量并执行i + 1 在Python 中不是一个好习惯。阅读 Ned Batchelder 的Loop Like A Native。每当您编写 Python(尤其是循环)时,请查看是否有 惯用 方法来实现这一点。这就是 Python 等语言的真正魅力所在。另外,避免在循环时修改列表的大小。

如果您只需要删除空字符串,只需使用filter(None, x)。

xStr = ['INC123123123', 'INC222222222', 'INC333333333', 
        'INC444444444', 'INC555555555', '', '']

print(list(filter(None, xStr)))

filters 的签名是(function_to_apply, list_of_inputs)。所以,如果你使用

lambda x: x != ''

那么它只会选择非空的stings。与使用 None 相比,这是一种更冗长的方式。如果要反转它,请使用

lambda x: x == ''`

所以,如果你使用list(filter(lambda x: x == '', xStr)),它只会选择空字符串。

【讨论】:

  • 比列表理解更快,我在您的答案中添加了一个示例。 +1
  • 哇,感谢 Nishant - 我不知道 filter 命令这有很大帮助!就我自己的知识而言,有一个与此相反的命令。假设我只想过滤“无”
  • @AzySır,是的,没有什么是硬编码的。我应该已经展示了这样做的明确方式:-)
【解决方案2】:

这个怎么样?它过滤掉所有长度为0的字符串

def foo():
    x = ['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555', '', '']
    x =  list(filter(len, x))
    y = x
    return y

print(foo())

【讨论】:

    【解决方案3】:

    您试图在遍历列表时修改列表,这会导致问题。相反,您应该执行以下操作:

    def readFile():
        with open('incidents.txt') as f:
            x = f.read().splitlines()
            print(x)
    
        y = [a for a in x if a]
        return y
    

    【讨论】:

      【解决方案4】:

      也许你应该改用if inc == ''。

      【讨论】:

        【解决方案5】:

        单行使用列表推导:

        xStr = ['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 
                'INC555555555', '', '']
        print([x for x in xStr if x])
        

        输出:

        ['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555']
        

        【讨论】:

          【解决方案6】:

          你会使用过滤功能来删除空白字符串。

          def readFile():
              with open('try.txt') as f:
                  x = f.read().splitlines()
                  print(x)
              i = 0
              y = list(filter(None, x))    
              return y
          

          【讨论】:

            【解决方案7】:

            使用过滤器删除您要删除的特定类型的字符串。您可以使用 lambda 和 filter 来添加条件以删除任何特定类型的字符串。

            line = ['INC123123123', 'INC222222222', 'INC333333333', 
                    'INC444444444', 'INC555555555', '', '']
            
            line_mod = filter(lambda x: x != '', line)
            print line_mode
            

            输出:

            ['INC123123123', 'INC222222222', 'INC333333333', 'INC444444444', 'INC555555555']
            

            【讨论】:

              【解决方案8】:

              在迭代时从列表中删除元素不是一个好主意。

              试试:

              def readFile():
                  with open('incidents.txt') as f:
                      result = []
                      for line in f:
                          line = line.strip()
                          if line:
                              result.append(line)
                  return result
              

              【讨论】:

                猜你喜欢
                • 2022-10-23
                • 1970-01-01
                • 2017-04-25
                • 1970-01-01
                • 2015-04-07
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多