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

因此,我在這里要做的是打開一個包含一些文本的文件,並將其拆分為幾行,然后刪除那些以@開頭的行。 但是,取而代之的是,在某些時候它只是不會刪除更多的行,而在內容var中有些則沒有'@'結尾。 為什么?

在迭代列表時,切勿刪除列表中的項目。

為什么不執行以下操作:

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

迭代容器時,請勿修改容器。

您在許多方面都過於復雜了:無需顯式關閉文件( with -block with使用); 您無需使用“原始字符串”來指定“ @”; 您不需要發明“開始於”; 您不需要自己將文件分成幾行(只需遍歷文件一次就可以產生一行數據),也不需要編寫自己的循環。

您想要的是文件中以“ @”開頭的行的列表。 因此,直接要求:

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

因為您在遍歷列表時會搞砸列表。 另外,您應該遍歷文件以逐行獲取它。 另外,您甚至都不會寫出結果。

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)

您不應該修改要迭代的內容。 我對您的代碼進行了一些更改,並在此處添加了注釋。

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的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM