![](/img/trans.png)
[英]How to sort 2D array column by ascending and row by descending in Python 3
[英]How to find the row and column of element in 2d array in python?
我有這個二維數組:
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]]
現在,我想要搜索一個元素,output 將是它的列和行示例。
輸入要搜索的數字:40
在第 3 行第 4 列中找到第 40 號
輸入數字:100
找不到號碼
像這樣的東西? 提前致謝
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}
如果列數如示例所示是恆定的,則可以使用以下代碼進行搜索。
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)
您可以使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.