简体   繁体   English

Python list.remove()似乎出现故障

[英]Python list.remove() seems to malfunction

fileHandle = open(filedir, 'r')
content = fileHandle.read().split('\n')
for e in content:
    if (e == '' or (e[0] != r"@"):
        content.remove(e)
fileHandle.close()

So, what I'm trying to do here is open a file with some text and split it into lines, and then remove those lines that doesn't start with @. 因此,我在这里要做的是打开一个包含一些文本的文件,并将其拆分为几行,然后删除那些以@开头的行。 But instead, at some point it just doesnt take off more lines and some without the '@' end in the content var. 但是,取而代之的是,在某些时候它只是不会删除更多的行,而在内容var中有些则没有'@'结尾。 Why? 为什么?

Never remove items of a list while iterating over it. 在迭代列表时,切勿删除列表中的项目。

Why not just do the following: 为什么不执行以下操作:

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

Don't modify a container while you're iterating over it. 迭代容器时,请勿修改容器。

You're over-complicating this in many ways: you don't need to close the file explicitly (use a with -block); 您在许多方面都过于复杂了:无需显式关闭文件( with -block with使用); you don't need to use a "raw string" to specify '@'; 您无需使用“原始字符串”来指定“ @”; you don't need to invent "starts with"; 您不需要发明“开始于”; you don't need to split the file into lines yourself (just iterating over the file yields the data a line at a time) and you don't need to write your own loop. 您不需要自己将文件分成几行(只需遍历文件一次就可以产生一行数据),也不需要编写自己的循环。

What you want is a list of the lines in the file that start with '@'. 您想要的是文件中以“ @”开头的行的列表。 So, ask for that directly: 因此,直接要求:

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

Because you're screwing with the list as you're iterating over it. 因为您在遍历列表时会搞砸列表。 Plus, you should be iterating over the file to get it line by line. 另外,您应该遍历文件以逐行获取它。 Plus, you're not even writing the results out. 另外,您甚至都不会写出结果。

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)

You shouldn't modifying what you're iterating over. 您不应该修改要迭代的内容。 I've made some changes to your code and reposted it here with comments. 我对您的代码进行了一些更改,并在此处添加了注释。

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

This is just to illustrate the [:] operator. 这只是为了说明[:]运算符。 I'd still recommend Ignacio's solution over this. 我仍然会推荐Ignacio的解决方案。

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

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