我想檢查陣列中的任何值是否大于某個閾值,.... 做點什么
但似乎以下代碼中的 if 回圈不起作用。即使條件得到滿足,它也不會在 if 回圈中列印“是”。知道為什么嗎?
import random
import numpy as np
data = []
for i in range(0,10):
val = random.randint(0,110)
data.append(val)
data_np = np.array(data)
if all(i>=100 for i in data_np):
print('yes')
print(data_np)
uj5u.com熱心網友回復:
import numpy as np
arr = np.random.randint(0,30,10)
threshold = 20
mask = arr > threshold
print("arr", arr)
if True in mask:
print("yes, elements above threshold are :", arr[mask])
else:
print("No elements are above threshold")
uj5u.com熱心網友回復:
對于 numpy 陣列,請在掩碼上使用該.any
方法,而不是遍歷陣列:
data_np = np.random.randint(0, 110, 10)
if (data_np >= 100).any():
print('yes')
uj5u.com熱心網友回復:
將所有替換為任何。
if any(i>=100 for i in data_np):
更多資訊:您想知道任何數字,并非所有數字都更大或不更大。所以你應該使用 ,any, 函式而不是 ,all,。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507385.html