Reputation: 23
So I have a matrix of 3xn. Something like
A=[[1,2,3],
[6,2,5],
[8,1,7],
[2,9,8],
[1,9,3],
[1,4,3]]
and another list of B= [1,2,5,6,8,9]
So, if every element from A[i] is in list B then I have to delete the row. Eg. row 2,4 will need to be removed.
I wrote something like.
copy=[]
for i in A:
for j in B:
if int(j) in i:
for k in B[B.index(j):]:
if int(k) in i:
for l in B[B.index(k):]:
if int(l) in i:
copy.append(i)
This keeps returning recurring values. It also removes more than what I have already written. What am I doing wrong?
I also tried
for i in A:
copy=[x for x in i if x not in B]
copy=np.array(copy)
final.append(copy)
But it doesn't work.
Note: I am using numpy array for A and list for B so I always need to convert between them when I am doing comparing.
Upvotes: 1
Views: 704
Reputation: 29
Loop through each sublist inside list "A". For each item in that sublist, we check if it is present in list "B". If it is, we increment count to 1. When count reaches the length of our sublist, we remove that sublist by using the .remove() method, which takes an index, in our case, the index is that of the sublist inside the list "A".
for lst in A:
count=0
for subList_itm in lst:
if subList_itm in B:
count = count+1
if count== len(lst):
A.remove(lst)
count=0
print(A)
Upvotes: 1
Reputation: 6728
Concept
Iterate through all of the elements inside A
, and check if each array is a subset of B
. If it is not then put the array into a result array.
Code
A=[[1,2,3],[6,2,5],[8,1,7],[2,9,8],[1,9,3],[1,4,3]]
B=[1,2,5,6,8,9]
set_B=set(B)
result=[]
for arr in A:
if not set(arr).issubset(set_B):
result.append(arr)
print(result)
Upvotes: 0
Reputation: 260300
It is quite straightforward with numpy arrays, use isin
to identify values present in B, then aggregate as a single boolean with all
to get rows where all values are present, invert the mask with ~
and slice:
A = np.array([[1,2,3],
[6,2,5],
[8,1,7],
[2,9,8],
[1,9,3],
[1,4,3]])
B = np.array([1,2,5,6,8,9])
# or as list
B = [1,2,5,6,8,9]
A2 = A[~np.isin(A, B).all(1)]
output:
array([[1, 2, 3],
[8, 1, 7],
[1, 9, 3],
[1, 4, 3]])
intermediates:
np.isin(A, B)
array([[ True, True, False],
[ True, True, True],
[ True, True, False],
[ True, True, True],
[ True, True, False],
[ True, False, False]])
np.isin(A, B).all(1)
array([False, True, False, True, False, False])
~np.isin(A, B).all(1)
array([ True, False, True, False, True, True])
Upvotes: 1