0

I have an 2D array:

2d_arr = [[a,b,c,d],[a,b],[c,d],[a,f]]

And another array:

arr = [a,w,b,x]

I want to compare every element in the 2D array (2d_arr) with the array (arr) and get the output as a new 2D array like this: (if the 2D array elements match the array put 1 else 0)

[a,w,b,x]
[1,0,1,0]
[1,0,1,0]
[0,0,0,0]
[1,0,0,0]

I have tried the follow:

for i in range(len(2d_arr)):
   for j in range(len(2d_arr[i])):
      if 2d_arr[i][j] == arr[i]
         .....

I know the arr[i] from the last line is wrong but how would i iterate??

1 Answer 1

2

You can use a list comprehension:

arr_2d = [['a','b','c','d'],['a','b'],['c','d'],['a','f']]
arr = ['a','w','b','x']

[[int(x in a) for x in arr] for a in arr_2d]

[[1, 0, 1, 0], [1, 0, 1, 0], [0, 0, 0, 0], [1, 0, 0, 0]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.