Reputation: 39
I have this 2d array :
import numpy as np
R = int(input("Enter the number of rows:")) //4
C = int(input("Enter the number of columns:")) //5
randnums= np.random.randint(1,100, size=(R,C))
print(randnums)
[[98 25 33 9 41]
[67 32 67 27 85]
[38 79 52 40 58]
[84 76 44 9 2]]
Now, i want to happen is that i will search an element and the output will be its column and rows example.
enter number to search : 40
Number 40 found in row 3 column 4
enter number : 100
number not found
something like this ? thanks in advance
Upvotes: 0
Views: 6824
Reputation: 561
You can use numpy.where
function.
r = np.random.randint(1,10, size=(5,5))
# array([[6, 5, 3, 1, 8],
# [3, 9, 7, 5, 6],
# [6, 2, 5, 5, 8],
# [1, 5, 1, 1, 1],
# [1, 6, 5, 8, 6]])
s = np.where(r == 8)
# the first array is row indices, second is column indices
# (array([0, 2, 4], dtype=int64), array([4, 4, 3], dtype=int64))
s = np.array(np.where(r == 8)).T
# transpose to get 2d array of indices
# array([[0, 4],
# [2, 4],
# [4, 3]], dtype=int64)
Upvotes: 1
Reputation: 2584
If the number of columns will be constant as shown in the example, you can search using below code.
a = [[98, 25, 33, 9, 41],
[67, 32, 67, 27, 85],
[38, 79, 52, 40, 58],
[84, 76, 44, 9, 2]]
a_ind = [p[x] for p in a for x in range(len(p))] # Construct 1d array as index for a to search efficiently.
def find(x):
return a_ind.index(x) // 5 + 1, a_ind.index(x) % 5 + 1 # Here 5 is the number of columns
print(find(98), find(58), find(40))
#Output
(1, 1) (3, 5) (3, 4)
Upvotes: 1
Reputation: 3856
l = [[98, 25, 33, 9, 41],
[67, 32, 67, 27, 85],
[38, 79, 52, 40, 58],
[84, 76, 44, 9, 2]]
def fnd(l,value):
for i,v in enumerate(l):
if value in v:
return {'row':i+1,'col':v.index(value)+1}
return {'row':-1,'col':-1}
print(fnd(l,40))
{'row': 3, 'col': 4}
Upvotes: 1