2014-01-13 126 views
1

我剛剛瞭解了列表理解,但我無法完全理解它在正確的上下文中工作。 我的for循環: 結果和實例都列出如何在Python中使用列表理解for循環python

for i in results: 
    instances.remove(i) 
    results.remove(i) 

我試圖[i for i in one if one.count(i)<2 if two.count(i)<2],但它不工作。我可以用它來處理它們中的一個,[i for i in one if one.count(i)<2],但我想將它們兩者合併到同一個循環中。有人能告訴我最簡單的方法嗎?

+3

迭代時不要修改列表。 – aIKid

+1

您的'for'循環可能無法正常工作,因爲您在循環時修改了'results' –

+0

您能給我們提供示例輸出和輸入嗎? – aIKid

回答

4

假設results是一個列表。你似乎試圖做到這一點

for i in results: 
    instances.remove(i) 
del results[:] 

列表理解是在這裏使用的錯誤的東西。你並沒有試圖從一個序列中創建一個新的列表。

這個循環是相似的,但會刪除相反的順序

while results: 
    instances.remove(results.pop()) 
+0

或'results = []'來猜測。 – aIKid

+0

@alKid,對於第二種解決方案,您不一定要重新結合「結果」 –

+2

+1。酷 – aIKid

1

您需要先結果出來的for循環的實例。將它設置在它之後,然後在for循環完成後將其刪除。