[英]Finding consecutive and identical integer into a vector
I have vectors with 0 and 1.我有 0 和 1 的向量。
a = np.array([1,1,0,0])
b = np.array([1,0,0,1])
c = np.array([0 1 1 0])
d = np.array([0 1 0 1])
I would like to implement a function checking if the 1 are consecutive in the vector by disregarding the end of the vector, ie last element wih first element.我想实现一个 function 通过忽略向量的结尾(即第一个元素的最后一个元素)来检查向量中的 1 是否连续。 Expected results will be:
预期结果将是:
check(a) --> True
check(b) --> True
check(c) --> True
check(d) --> False
The easy solution will be to scroll through each vector.简单的解决方案是滚动浏览每个向量。 However I feel that an easier and smarter is doable with some np.diff or np.nonzero combination.
但是,我觉得使用一些 np.diff 或 np.nonzero 组合可以更轻松、更智能。 Any idea?
任何想法?
Thanks a lot.非常感谢。
You could use np.roll + np.logical_and + np.count_nonzero你可以使用np.roll + np.logical_and + np.count_nonzero
import numpy as np
def check(arr):
return np.count_nonzero(np.logical_and(np.roll(arr, 1), arr)) > 0
a = np.array([1, 1, 0, 0])
b = np.array([1, 0, 0, 1])
c = np.array([0, 1, 1, 0])
d = np.array([0, 1, 0, 1])
print(check(a))
print(check(b))
print(check(c))
print(check(d))
Output Output
True
True
True
False
Maybe you can try something like this,也许你可以尝试这样的事情,
def check(k):
return any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])
np.where(k==1)
, this will return a list of indices where your vector is 1. np.where(k==1)
,这将返回您的向量为 1 的索引列表。
np.diff(np.where(k==1))
, this will evalute the difference between consequative indices where your vector is 1. np.diff(np.where(k==1))
,这将评估向量为1的结果索引之间的差异。
Finally any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])
this will check if there are consecutive 1's.最后
any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])
这将检查是否有连续的 1。 Either if their difference is 1 or length of your vector - 1.如果它们的差异是 1 或向量的长度 - 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.