簡體   English   中英

Python從列表中刪除項目

[英]Python remove items from list

我在從列表中刪除項目時遇到了一些麻煩。 我正在尋找更優雅的解決方案。 優選地,在一個for環路​​或濾波器中的解決方案。

這段代碼的目的:從配置句柄中刪除所有空條目和所有以“#”開頭的條目。

目前,我正在使用:

# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]

# Strip comment items from the configHandle
for item in configHandle:
    if item.startswith('#'):
        configHandle.remove(item)

# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle

這可行,但是我認為這是一個令人討厭的解決方案。

當我嘗試:

# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]

# Strip comment items and empty items from the configHandle
for item in configHandle:
    if item.startswith('#'):
        configHandle.remove(item)
    elif len(item) == 0:
        configHandle.remove(item)

但是,這失敗了。 我不知道為什么。

有人可以將我推向正確的方向嗎?

因為您在迭代列表時正在更改列表。 您可以使用列表理解來解決此問題:

configHandle = [i for i in configHandle if i and not i.startswith('#')]

同樣,對於打開文件,您最好使用with語句,該語句會自動在塊末尾1關閉文件:

with open('config.conf') as infile :
   configHandle = infile.splitlines()
   configHandle = [line for line in configHandle if line and not line.startswith('#')]

1.因為不能保證垃圾收集器可以收集外部鏈接。 並且您需要顯式關閉它們,這可以通過調用文件對象的close()方法來完成,或者如前所述,使用with語句以更Python的方式進行close()

迭代時不要刪除項目,這是一個常見的陷阱

不允許您修改要迭代的項目。

相反,您應該使用諸如filter或list comprehensions之類的東西。

configHandle = filter(lambda a: (a != '') and not a.startswith('#'), configHandle)

您的filter表達式很好; 僅包括您要查找的其他條件:

configHandle = filter(lambda a: a != '' and not a.startswith('#'), configHandle)


如果您不想使用filter ,則還有其他選擇,但是,正如其他答案中所述,在遍歷列表時嘗試修改列表是一個非常糟糕的主意。 對這些問題的答案計算器問題提供替代使用filter ,以基於一個條件列表中刪除。

暫無
暫無

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

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