在 python 中,当您迭代某事物时,您会从该事物中获取元素。您没有获得索引(至少不是自动获得)
In [262]: for i in ['a','b','c']:
...: print(i)
...:
a
b
c
In [264]: for i in np.arange(10,20,2):print(i)
10
12
14
16
18
In [265]: for i in range(4):print(i)
0
1
2
3
最后一个表达式有效地迭代列表[0,1,2,3]。
所以表达式:
for i in arr:
print(arr[i])
没有意义。 i 是 arr 的元素,而不是索引。
这应该可行:
for a in arr:
if abs(a - val) < temp:
temp = abs(a - val)
#pos = i
但是由于您需要索引i,因此首选的python迭代是:
for i, a in enumerate(arr):
av = abs(a - val)
if av < temp:
temp = av
pos = i
enumerate 在哪里添加一个索引。把这个enumerate 放在手边。
但是这是 numpy 我们不需要迭代(至少在 Python 中不需要)
In [266]: x = np.linspace(0, 2*np.pi, 50, endpoint=True)
In [267]: x<(2*np.pi/2)
Out[267]:
array([ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False], dtype=bool)
In [268]: np.where(x<(2*np.pi/2))
Out[268]:
(array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24], dtype=int32),)
In [269]: x[24:26]
Out[269]: array([ 3.07747852, 3.20570679])
我们可以用一条语句将x的每个元素与目标进行比较,找到最大的。
In [272]: np.max(np.where(x<(2*np.pi/2)))
Out[272]: 24
In [273]: np.argmin(x<(2*np.pi/2))
Out[273]: 25
有多种方法可以确定 < 测试为 True 或切换为 False 的最后一个元素。