Reputation: 3
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??
Upvotes: 0
Views: 75
Reputation: 15071
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]]
Upvotes: 2