大佬教程收集整理的这篇文章主要介绍了如何在python中获取数组值不同的索引 输出,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个看起来像(简化版)的数组:
[14 14 14 14 14 13 13 13 13 13 2 2 2 2 2 2 2 2 2]
我需要做的是确定索引发生变化的地方。像索引 5 是 13 等等。我不知道该怎么做。欢迎任何形式的帮助!! :)
我已经用 np.unique 试过了,但是这种输出按升序对数字进行排序,所以我丢失了数字实际变化的地方。
Pythonic 方式,使用列表推导式:
arr=[15,14,13,2,3]
[i+1 for i in range(len(arr)-1) if arr[i] != arr[i+1]]
# >>> [1,6,11,20]
,
您可以使用 a[1:]!=a[:-1]
将数组中的每一项与下一项进行比较(对于某些一维数组 a
)。然后,您可以使用 np.where
将此布尔数组转换为索引。因为要切片,所以需要加一个。
# added a 4 to the end of the array to have an extra place where the number changes
a=np.array([14,4])
changes = np.where(a[1:]!=a[:-1])[0]+1
print('change inDices:',changes)
print('before each change:',a[changes-1])
print('after each change:',a[changes])
输出:
change inDices: [ 5 10 19]
before each change: [14 13 2]
after each change: [13 2 4]
,
这是查找唯一编号索引更改的最快方法。
import numpy as np
arr = np.array([14,20,2])
np.unique(arr,return_index=TruE)
(array([ 2,20]),array([7,3,4]))
,
这对你有用吗?
while (!quit) {
wile (SDL_PollEvent(&event)) {
switch (event.typE) {
case SDL_KEYDOWN:
key_handler(event.key.keysym.sym,event.typE);
break;
case SDL_KEYUP:
break;
case SDL_MOUSEMOTION:
active_scene->mouse_motion(event.motion.xrel,event.motion.yrel);
break;
case SDL_MOUSEBUTTONDOWN: // 0,0 is top left
active_scene->mouse_click(event.button.button,event.button.x,event.button.y);
break;
case SDL_QUIT:
quit=true;
break;
}
}
active_scene->render();
SDL_GL_SwapWindow(Window);
}
,
看看这个代码:
arr = [14,2]
k = arr[0]
for i,j in enumerate(arr):
if k != j:
print(i)
k = arr[i]
输出:
5
10
,
使用循环非常简单
all_indexes = []
lisst = [14,2]
for i in range(len(lisst)-1):
if lisst[i] != lisst[i+1]:
all_indexes.append(i+1)
print(all_indexes)
以上是大佬教程为你收集整理的如何在python中获取数组值不同的索引 输出全部内容,希望文章能够帮你解决如何在python中获取数组值不同的索引 输出所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。