Lucy Brown
Lucy Brown

Reputation: 43

How to delete a row from a list of a list of a list

How do I delete the row if it contains a specific values e.g.

actual = [  [ [1,1.4567,3],[4,5,6],[7,1.4567,8],[1,2,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,1.4567,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]

expected = [  [ [1,3,3],[4,5,6],[7,5,8],[1,7,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,2,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]

I want it to look throw actual and if it finds a 1.4567 then to delete that row and the corresponding row from expected e.g. from above

I want row [1,1.467,3] to be deleted from the list as well as the corresponding [1,3,3] from the expected list #because its in the same position. Again i want the [7,1.4567,8] to be deleted as well as the corresponding [7,5,8]. Again i want the [1,1.4567,3] to be deleted as-well as the [1,2,3] in the expected list.

I've been trying to use axis and a for loop but it wont work, and i cant think of any other method

In the end I want it to print out (using the example above):

actual = [  [ [4,5,6],[1,2,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,2,4],[2,4,6],[5,6,7]  ]   ]

expected = [  [ [4,5,6],[1,7,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,2,4],[2,4,6],[5,6,7]  ]   ]

import numpy as np

actual = [  [ [1,1.4567,3],[4,5,6],[7,1.4567,8],[1,2,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,1.4567,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]

expected = [  [ [1,3,3],[4,5,6],[7,5,8],[1,7,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,2,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]

actual1 = np.array(actual)
expected1 = np.array(expected)


for i in actual[i]:
keep_idx = np.all(actual1[i] != 1.4567, axis=1)

expected = expected1[keep_idx]
actual = actual1[keep_idx]

Upvotes: 0

Views: 49

Answers (2)

Dan
Dan

Reputation: 1587

You could try something like this:

actual = [  [ [1,1.4567,3],[4,5,6],[7,1.4567,8],[1,2,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,1.4567,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]

expected = [  [ [1,3,3],[4,5,6],[7,5,8],[1,7,3] ]  ,  [ [1,2,3],[4,5,6],[7,7,8],[1,2,3],[1,2,4],[2,4,6],[5,6,7]  ]   ]


target = 1.4567
for ix1, inner_list in enumerate(actual):
    for ix2, lst in enumerate(inner_list):
        if target in lst:
            actual[ix1].pop(ix2)  # remove from actual
            expected[ix1].pop(ix2)  # remove from expected
            continue

print(actual)
print(expected)

Output:

[[[4, 5, 6], [1, 2, 3]], [[1, 2, 3], [4, 5, 6], [7, 7, 8], [1, 2, 4], [2, 4, 6], [5, 6, 7]]]
[[[4, 5, 6], [1, 7, 3]], [[1, 2, 3], [4, 5, 6], [7, 7, 8], [1, 2, 4], [2, 4, 6], [5, 6, 7]]]

Upvotes: 1

David Kong
David Kong

Reputation: 638

does this work?

for m,n in zip(actual,expected):
  for i,j in zip(m,n):
    print(i,j)
    if 1.4567 in i:
        m.remove(i)
        n.remove(j)

Upvotes: 0

Related Questions