2016-04-21 135 views
1

我必須刪除行列表中項目的索引,其中lines[0]的項目不在標題中。Python:按索引彈出列表列表中的項目

輸入如下:

headers = ['internal_id', 'default_code', 'ean13', 'supplier_id', 'product_qty'] 
lines = [['default_code', 'fld_code', 'test'],[1212, 4545, 'test1'],[45, 787, 'test2']] 

預期輸出如下:

lines = [['default_code'],[1212],[45]] 

我已經試過到目前爲止做的是在這裏:

for x in lines[0]: 
    if x not in headers: 
     for line in lines[0]: 
      line.pop(line.index(x)) 
print lines 

這尚未產生所需的產出。請幫助。

+0

既然你改正了語言凱文Cruijssen,我不明白...對我來說「預期的輸出」是不兼容的解釋「我必須刪除行列表中的項目由行項目索引[0]不在標題中「 – Vince

回答

1

我校根據您的代碼:

for i, x in reversed(list(enumerate(lines[0]))): 
    if x not in headers: 
     for line in lines: 
      line.pop(i) 
print lines 

輸出:

[['default_code'], [1212], [45]] 
+0

喬,我編輯了我的答案。它會循環線[0]並反轉並處理超過2個元素。但是,如果問題標記爲已回答,則不應對其進行編輯。 – qvpham

+0

感謝它正在工作....! – Jothimani

0

使用列表理解(您也可以使用filter)。

lines = [line for line in lines if line[0] in headers] 

輸出:

[['default_code', 'fld_code']] 

如果你想要的是一個 「手動」 循環使用list.remove

for x in lines: 
    if x[0] not in headers: 
     lines.remove(x) 
+0

@我需要刪除線條[0]中的缺失項目以及標題中的所有列表,以及線條[0]的缺失項目索引的相同索引中的所有列表。 – Jothimani

0

,如果你想使用彈出,你必須使用索引,然後沒有問題的話,最好從頭開始。

for x in range(len(lines)-1,-1,-1): 
    if lines[x][0] not in headers: 
     lines.pop(x)  
print lines 

我不知道你的項目是什麼,但你應該考慮使用一個詞典。

0

這是你想寫:)

for x in lines[0]: 
    if x not in headers: 
     n = lines[0].index(x) 
     for line in lines: 
      line.remove(line[n]) 
print lines 

你是那種親密的代碼。如果你想在某個位置「刪除」一個元素,你不想使用pop。有更優雅和更短的解決方案,但這個適合你的編碼風格。看看Python中的列表理解,它非常強大。

0
for line in lines[0]: 
     line.pop(line.index(x)) 

我希望在循環線是持有的字符串類型的值。我們不能在字符串中使用pop。糾正我,如果我錯了。