# 遍历numpy ndarray，管理第一个和最后一个元素

ShanZhengYang

``````import numpy as np
arr = np.array([2, 3, 4, 7, 7, 4, 4, 5, 1, 1, 9, 9, 9, 4, 25, 26])
``````

``````for i in range(len(arr)):
if (arr[i] == arr[i+1]):
print( "Match at entry %d at array location (%d)" % (arr[i], i))
else:
pass
``````

``````Match at entry 7 at array location (3)
Match at entry 7 at array location (4)
Match at entry 4 at array location (6)
Match at entry 1 at array location (9)
Match at entry 9 at array location (11)
Match at entry 9 at array location (12)
``````

`````` if ((arr[i] == arr[i+1]) and (arr[i] == arr[i-1]))
``````

``````>>> arr = np.array([2, 2, 3, 4, 7, 7, 4, 4, 5, 1, 1, 9, 9, 9, 4, 25, 26, 26])
``````

``````>>> np.where(arr[:-1] == arr[1:])[0]
array([ 0,  4,  6,  9, 11, 12, 16])
``````

``````arr = np.array([2, 2, 3, 4, 7, 7, 4, 4, 5, 1, 1, 9, 9, 9, 4, 25, 26, 26])
matches = np.where(arr[:-1] == arr[1:])[0]
for index in matches:
for i in [index, index + 1]:
print("Match at entry %d at array location (%d)" % (arr[i], i))
``````

``````Match at entry 2 at array location (0)
Match at entry 2 at array location (1)
Match at entry 7 at array location (4)
Match at entry 7 at array location (5)
Match at entry 4 at array location (6)
Match at entry 4 at array location (7)
Match at entry 1 at array location (9)
Match at entry 1 at array location (10)
Match at entry 9 at array location (11)
Match at entry 9 at array location (12)
Match at entry 9 at array location (12)
Match at entry 9 at array location (13)
Match at entry 26 at array location (16)
Match at entry 26 at array location (17)
``````

``````>>> arr[:-1] == arr[1:]
array([ True, False, False, False,  True, False,  True, False, False,
True, False,  True,  True, False, False, False,  True], dtype=bool)
``````

``````>>> cond = arr[:-1] == arr[1:]
>>> np.where(cond)
(array([ 0,  4,  6,  9, 11, 12, 16]),)
``````

``````>>> np.where(cond)[0]
array([ 0,  4,  6,  9, 11, 12, 16])
``````

0 条评论