Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中返回矩阵中间索引的干净方法_Python_Arrays_Matrix - Fatal编程技术网

Python中返回矩阵中间索引的干净方法

Python中返回矩阵中间索引的干净方法,python,arrays,matrix,Python,Arrays,Matrix,需要一种干净的方法来找到矩阵中间的索引,如果没有“中间”,则是周围最大元素的索引。注意矩阵并不总是正方形的 例1。输入:[[1,2],[3,4]] (1,2) (3,4) 这将返回(1,1),因为围绕“中间”的最大元素是4 例2。输入:[[1,2,3],[4,5,6],[7,8,9] (1,2,3) (4,5,6) (7,8,9) 这将返回(1,1),因为这是矩阵中间的索引 如果能以一种干净的方式返回上述索引,我们将不胜感激 让你的矩阵是一个NumPy数组 import mumpy as np

需要一种干净的方法来找到矩阵中间的索引,如果没有“中间”,则是周围最大元素的索引。注意矩阵并不总是正方形的

例1。输入:
[[1,2],[3,4]]

(1,2)
(3,4)

这将返回(1,1),因为围绕“中间”的最大元素是4

例2。输入:
[[1,2,3],[4,5,6],[7,8,9]

(1,2,3)
(4,5,6)
(7,8,9)

这将返回(1,1),因为这是矩阵中间的索引


如果能以一种干净的方式返回上述索引,我们将不胜感激

让你的矩阵是一个NumPy数组

import mumpy as np
a = np.array([[1,2], [3,4]])
b = np.array([[1,2,3],[4,5,6],[7,8,9]])
c = np.random.random_integers(100, size=8).reshape(2, -1)
#array([[41, 61, 47, 51],
#       [40, 81, 23, 66]])
检查尺寸,提取“中心”,找到最大值及其坐标,调整:

def find_center(a):
    x = (a.shape[0] // 2 if a.shape[0] % 2 else a.shape[0] // 2 - 1, 
         a.shape[0] // 2 + 1)
    y = (a.shape[1] // 2 if a.shape[1] % 2 else a.shape[1] // 2 - 1, 
         a.shape[1] // 2 + 1)
    center = a[x[0]:x[1], y[0]:y[1]]
    argmax = np.unravel_index(center.argmax(), center.shape)
    return argmax[0] + x[0], argmax[1] + y[0] # Adjust 
测试:

find_center(a)
#(1, 1)
find_center(b)
#(1, 1)
find_center(c)
#(1, 1) - 81!
在纯Python中:

def mid(n): return {(n-1)//2,n//2}
max(((i,j) for i in mid(len(a)) for j in mid(len(a[0]))),
    key=lambda ij: a[ij[0]][ij[1]])

定义“干净”。不是一百行代码就可以开始了。这些矩阵总是正方形吗?不,不是。你尝试过什么吗?获取“中间”的索引应该很容易。