2015-11-23 247 views
2

我遇到了一個問題,我的代碼中循環停止運行,一旦它從列表中刪除列表。遍歷列表python

data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]] 

for word_set in data: 
    if word_set[-1]!="hello": 
     data.remove(word_set) 
print(data) 

我期望的輸出是

[['why', 'why', 'hello'], ['why', 'cry', 'hello']] 

但輸出

[['why', 'why', 'hello'], ['why', 'hi', 'sllo'], ['why', 'cry', 'hello']] 

如何使循環下去,直到列表的末尾?

回答

1
>>> data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]] 
>>> y = [] 
>>> for subData in data: 
     for dataItem in subData: 
      if dataItem == "hello": 
       y.append(subData) 
>>> y 
[['why', 'why', 'hello'], ['why', 'cry', 'hello']] 
4

這是因爲,當您刪除第二個項目(其索引爲1)時,它後面的項目向前移動。在下一次迭代中,索引是2.它應該指向["why","hi","solo"]。但自項目向前移動後,它指向["why","cry","hello"]。這就是爲什麼你得到錯誤的結果。

它不建議刪除列表中的項目,同時遍歷列表。

您可以創建一個新的列表(在第一個答案提及),或使用filter功能。

def filter_func(item): 
    if item[-1] != "hello": 
     return False 
    return True 

new_list = filter(filter_func, old_list) 
1
filter(lambda x : x[-1] =="hello",[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]]) 

OR

reduce(lambda x,y : x + [y] if y[-1]=="hello" else x ,[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]],[]) 

OR

[i for i in [["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]] if i[-1]=="hello"] 
2

記住

data = [["list", "in","a list"],["list", "in","a list"],["list", "in","a list"]] 
#data[0] will return ["list", "in","a list"] 
#data[0][0] will return "list" 
#remember that lists starts with '0' -> data[0] 
1
data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]] 

for word_set in data[:]: 
    if word_set[-1]!= "hello": 
     data.remove(word_set) 
print(data) 

不要迭代原點數據,但重複(data [:])。因爲當從列表中刪除項目時,項目的索引將會改變。從數據中刪除時,列表索引中的["why","why","bell"]爲1。 ["why","hi","sllo"]中的數據索引將爲1.下一個迭代索引爲2,因此["why","hi","sllo"]已通過並檢查["why","cry","hello"]

+0

請添加一些評論,爲什麼你認爲這段代碼是答案,因爲它的立場,這個答案不是很有用。 –