![](/img/trans.png)
[英]Finding identical consecutive entries in a list and finding how many consecutive entries there are
[英]Finding consecutive and identical integer into a vector
我有 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])
我想实现一个 function 通过忽略向量的结尾(即第一个元素的最后一个元素)来检查向量中的 1 是否连续。 预期结果将是:
check(a) --> True
check(b) --> True
check(c) --> True
check(d) --> False
简单的解决方案是滚动浏览每个向量。 但是,我觉得使用一些 np.diff 或 np.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
True
True
True
False
也许你可以尝试这样的事情,
def check(k):
return any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])
np.where(k==1)
,这将返回您的向量为 1 的索引列表。
np.diff(np.where(k==1))
,这将评估向量为1的结果索引之间的差异。
最后any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])
这将检查是否有连续的 1。 如果它们的差异是 1 或向量的长度 - 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.