我希望列表中元素的位置与下一个元素不同
nums = np.array(["cat","cat","dog","dog","dog","goldfish","bee","bee","cat","cat"])
所以我在列表中使用zip和枚举
print [c for a,b,c in zip(nums, nums[1:],enumerate(nums)) if a != b]
[(1, 'cat'), (4, 'dog'), (5, 'goldfish'), (7, 'bee')]
我只想要这个职位
>>[1,4,5,7]
如何在这里删除元组?或者是否有更好的(以更快的方式)获得列表中不同元素的位置?
答案 0 :(得分:3)
只需比较1偏移切片并获得不匹配的索引 -
np.flatnonzero(nums[1:] != nums[:-1])
答案 1 :(得分:3)
如果您正在寻找非 numpy解决方案:
In [19]: a = ["cat","cat","dog","dog","dog","goldfish","bee","bee","cat","cat"]
In [20]: [x for x in range(len(a)-1) if a[x] != a[x+1]]
Out[20]: [1, 4, 5, 7]