我正在學習 python 和 numpy。在嘗試預測結果以檢查我的理解時,我遇到了這個:
import numpy as np
x = np.arange(1,10).reshape(3,3)
np.where(x>5) == (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))
和相關的錯誤我現在明白為什么了。
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我想出了這個:
all(map(np.array_equal,
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])) ))
all([np.array_equal(v,t) for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
all([(v==t).all() for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
哪個作業,但在我看來有點乏味和難以閱讀。是否有更多 pythonic 或 numpy 方法來測驗元組中的陣列?
uj5u.com熱心網友回復:
你非常接近。以下作業:
np.array_equal(np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])))
np.array_equal具有在元組上廣播的能力。它還將陣列和序列視為等效的,因此您可以根據需要使用:
np.array_equal(np.where(x>5), ([1, 2, 2, 2], [2, 0, 1, 2]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317010.html
