Drop an element from a list (drop row from list of lists)

841 views Asked by At

I have a 2d array like this one:

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'],
]

I am interested in the rows containing the value '2TM' at its 2nd index. For example:

  • Joe has the value '2TM' at index 2 in the 2nd appearance of his data.
  • Tom has the value '2TM' at index 2 in the 1st appearance of his data.

Each time the value '2TM' appears in the data, I want to remove the next two rows. The example above would become the following:

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'],
]

I've tried using list.pop like so:

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

There are 2 answers

3
Daniyal Ahmed On

You would need to do something like this

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)

You were quite close but just missed the increment of x.

1
Zach Gates On

Use a while loop:

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