2017-08-30 179 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