เหตุผลสำหรับข้อยกเว้นคือว่าสายโดยปริยายand boolครั้งแรกในตัวถูกดำเนินการด้านซ้ายและ (ถ้าตัวถูกดำเนินการด้านซ้ายเป็นTrue) จากนั้นในตัวถูกดำเนินการด้านขวา ดังนั้นจะเทียบเท่ากับx and ybool(x) and bool(y)
อย่างไรก็ตามboolในnumpy.ndarray(ถ้ามันมีมากกว่าหนึ่งองค์ประกอบ) จะโยนข้อยกเว้นที่คุณได้เห็น:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
bool()โทรอยู่ในนัยandแต่ยังอยู่ในif, while, orเพื่อให้การใด ๆ ของตัวอย่างต่อไปนี้ก็จะล้มเหลว
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
มีฟังก์ชั่นอื่น ๆ อีกมากมายและงบในหลามที่ซ่อนboolสายเช่นเป็นเพียงวิธีการเขียนอีก2 < x < 10 2 < x and x < 10และandจะโทร:boolbool(2 < x) and bool(x < 10)
องค์ประกอบฉลาดเทียบเท่าandจะเป็นnp.logical_andฟังก์ชั่นในทำนองเดียวกันคุณสามารถใช้เป็นเทียบเท่าnp.logical_oror
สำหรับอาร์เรย์แบบบูล - และการเปรียบเทียบชอบ<, <=, ==, !=, >=และ>บนอาร์เรย์ NumPy กลับอาร์เรย์ NumPy บูล - คุณยังสามารถใช้องค์ประกอบที่ชาญฉลาดบิตฟังก์ชั่น (และผู้ประกอบการ): np.bitwise_and( &ผู้ดำเนินการ)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
และbitwise_or( |ผู้ประกอบการ):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
รายการฟังก์ชันตรรกะและไบนารีที่สมบูรณ์สามารถพบได้ในเอกสาร NumPy: