【问题标题】:Python list.remove() seems to malfunctionPython list.remove() 似乎出现故障
【发布时间】:2010-12-08 11:44:17
【问题描述】:
fileHandle = open(filedir, 'r')
content = fileHandle.read().split('\n')
for e in content:
    if (e == '' or (e[0] != r"@"):
        content.remove(e)
fileHandle.close()

所以,我在这里要做的是打开一个包含一些文本的文件并将其拆分为行,然后删除那些不以 @ 开头的行。但是,在某些时候,它只是不会删除更多行,而且有些行在内容变量中没有“@”结尾。为什么?

【问题讨论】:

    标签: python string file


    【解决方案1】:

    在迭代列表时切勿删除列表项。

    为什么不直接做以下事情:

    with open(filedir) as f:
        lines = [line.rstrip("\r\n") for line in f if line.startswith("@")]
    

    【讨论】:

    • 很好,唯一的问题是列表的每个元素都以 \n 结尾。有什么优雅的方法可以解决这个问题?
    • @SilentGhost:该死的,我每次都这么写。 readlines 不需要,我会编辑。
    • @kenny_knp:您可以使用rstrip 来删除尾随的换行符。
    • 这里有些人需要冷静一下。 @AndiDog 谢谢
    【解决方案2】:

    在迭代容器时不要修改它。

    您在许多方面过于复杂:您不需要明确关闭文件(使用with -block);您不需要使用“原始字符串”来指定“@”;你不需要发明“开始于”;您不需要自己将文件拆分成行(只需遍历文件一次产生一行数据),也不需要编写自己的循环。

    您想要的是文件中以“@”开头的行的列表。所以,直接问吧:

    with open(filedir, 'r') as fileHandle:
      content = [line for line in fileHandle if line.startswith('@')]
    

    【讨论】:

      【解决方案3】:

      因为您在迭代列表时搞砸了。另外,您应该遍历文件以逐行获取它。另外,你甚至没有把结果写出来。

      with open(filedir, 'r') as fileHandle:
        with open(outputfile, 'w') as outputHandle:
          for line in fileHandle:
            if not line or line.startswith('@'):
              continue
          outputHandle.write(line)
      

      【讨论】:

        【解决方案4】:

        您不应该修改您正在迭代的内容。我对您的代码进行了一些更改,并使用 cmets 在此处重新发布。

        fileHandle = open(filedir, 'r')
        content = (x.strip() for x in fileHandle.readlines()) # Get all the lines and use a genexp to strip out the spaces. 
        for e in content[:]: # Python idiom for "copy of a list"
            if (e == '' or (e[0] != r"@"):
                content.remove(e)
        fileHandle.close()
        

        这只是为了说明 [:] 运算符。我仍然会推荐 Ignacio 的解决方案。

        【讨论】:

          猜你喜欢
          • 2013-06-14
          • 2017-05-25
          • 1970-01-01
          • 1970-01-01
          • 2011-12-09
          • 1970-01-01
          • 1970-01-01
          • 2016-07-19
          • 1970-01-01
          相关资源
          最近更新 更多