5个回答

``````import numpy as np

ls = np.array([[1, 2, 3, 4],
[8, 7, 9, 6]])
number = 2.9  # 输入的数
ls_cul = ls - number  # 求距离
ls_abs = abs(ls_cul)  # 求绝对值
argmin = ls_abs.argmin()  # 求最小值位置
print('最接近的数:%d,位置:[%d,%d]' % (ls.reshape(-1)[argmin], argmin / ls.shape[0], argmin % ls.shape[1]))

``````

darklinboxs 回复justalun: 好像有点问题，我测试了一下，如果把数组的值8换成20,9换成10，然后输入一个20做判定，返回的是20.

``````# encoding: utf-8

from compiler.ast import flatten

arr = flatten([[1,2,3],[3,2,1],[4,5,6],[8,8,8]])
arr = zip(arr, map(lambda x : (x / 3, x % 3), range(0, len(arr))))
#换成这个可以运行的时候输入 n = input()
n = 4
arr.sort(key=lambda x: abs(x[0] - n))
print(arr[0])
``````

darklinboxs 报错了555，ModuleNotFoundError: No module named 'compiler'

`````` # encoding: utf-8
import collections

def flatten(x):
result = []
for el in x:
for i in el:
result.append(i)
print(result)
return result

arr = flatten([[1,2,3],[3,2,1],[4,5,6],[8,8,8]])
arr = zip(arr, map(lambda x : (x / 3, x % 3), range(0, len(arr))))
#换成这个可以运行的时候输入 n = input()
n = 4
arr.sort(key=lambda x: abs(x[0] - n))
print(arr[0])
``````