2017-08-30 176 views
0

(從列表的列表中丟棄行)我有一個二維數組像這樣的:從列表刪除一個元素

list_of_data = [ 
    ['Joe', 4, 4, 4, 5, 'cabbage', None], 
    ['Joe', 43, '2TM', 41, 53, 'cabbage', None], 
    ['Joe', 24, 34, 44, 55, 'cabbage', None], 
    ['Joe', 54, 37, 42, 85, 'cabbage', None], 

    ['Tom', 7, '2TM', 4, 52, 'cabbage', None], 
    ['Tom', 4, 24, 43, 52, 'cabbage', None], 
    ['Tom', 4, 4, 4, 5, 'cabbage', None], 

    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
] 

我對含有在其第二索引值'2TM'的行。例如:

  • Joe在其數據的第二次出現時在索引2處具有值'2TM'
  • 湯姆在其數據的第一次出現時在索引2處具有值'2TM'

每次數值中出現'2TM'的值,我想刪除下兩行。使用list.pop像這樣

list_of_data = 
    ['Joe', 4, 4, 4, 5, 'cabbage', None], 
    ['Joe', 43, '2TM', 41, 53, 'cabbage', None], 

    ['Tom', 7, '2TM', 4, 52, 'cabbage', None], 

    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
    ['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
] 

我已經試過:上面的示例將成爲繼

for row[x] in list_of_data: 
    if '2TM' in row: 
     list_of_data.pop[x+1:x+2] 

回答

1

你需要做這樣的事情

list_of_data = [['Joe', 4, 4, 4, 5, 'cabbage', None], 
['Joe', 43,'2TM', 41, 53, 'cabbage', None], 
['Joe', 24, 34, 44, 55, 'cabbage', None], 
['Joe', 54, 37, 42, 85, 'cabbage', None], 

['Tom', 7,'2TM', 4, 52, 'cabbage', None], 
['Tom', 4, 24, 43, 52, 'cabbage', None], 
['Tom', 4, 4, 4, 5, 'cabbage', None], 

['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
['Fred', 4, 4, 4, 5, 6, 'cabbage'], 
['Fred', 4, 4, 4, 5, 6, 'cabbage']] 
x=0 
for row in list_of_data: 
    if '2TM' in row: 
     list_of_data.pop(x+1) 
     list_of_data.pop(x+1) 
    x+=1 
print(list_of_data) 

你是相當接近但錯過了x的增量。

+0

'list.pop'會失敗,如果沒有兩個行(甚至一)行後含有''2TM''。例如,如果「list_of_data」的最後一行(或倒數第二行)包含「2TM」,則「list.pop」會引發異常。 –

+0

他提到後面兩行需要刪除。雖然支票可以用於最後一行 –

+1

@ZachGates我理解你的反對意見。而對於一般目的而言,你是對的:這種方法會在你描述的場景中引起反對。然而,我的數據集的固有/獨特的性質是,任何時候2TM出現在我的數據中,總是有2行需要刪除。所以這個.pop方法實際上對我的數據有效,即使它可能不適用於一般目的。 – TJE

1

使用while循環:

index = 0 

while index < len(list_of_data): 
    if list_of_data[index][2] == '2TM': 
     # check if the names are the same, as needed 
     del list_of_data[index + 1:index + 3] 

    index += 1 
+1

這個方法和下面的方法一樣。非常感謝您的意見。 – TJE