簡體   English   中英

如何有效檢查numpy數組包含給定范圍內的項目?

[英]How to check efficiently numpy array contains item within given range?

我有一個numpy的陣列,叫a ,我要檢查它是否包含在一個范圍內的項目,由兩個值規定。

import numpy as np
a = np.arange(100)

mintrshold=33
maxtreshold=66

我的解決方案:

goodItems = np.zeros_like(a)
goodItems[(a<maxtreshold) & (a>mintrshold)] = 1

if goodItems.any(): 
   print (there s an item within range)

您能建議我一種更有效的pythonic方法嗎?

Numpy數組不適用於pythonic a < x < b 但這有一個功能:

np.logical_and(a > mintrshold, a < maxtreshold)

要么

np.logical_and(a > mintrshold, a < maxtreshold).any()

在您的特定情況下。 基本上,您應該結合兩個元素操作。 尋找邏輯功能以獲取更多詳細信息

除了純粹的Numpy答案外,我們還可以使用itertools

import itertools

bool(list(itertools.ifilter(lambda x: 33 <= x <= 66, a)))

對於較小的數組,這已足夠:

bool(filter(lambda x: 33 <= x <= 66, a))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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