簡體   English   中英

將連續且相同的 integer 查找到向量中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM