在 Python 中獲取布林值的否定值
-
在 Python 中使用
not運算子計算否定布林值 -
使用來自
operator模組的operator.not_()函式來否定 Python 中的布林值 -
在 Python 中使用
~運算子來否定 NumPy 陣列的布林值 -
使用 NumPy 庫中的
bitwise_not()函式來否定布林值 -
使用 NumPy 庫中的
invert()函式來否定 Python 中的布林值 -
使用 NumPy 庫中的
logical_not()函式來否定 Python 中的布林值
Python 中有多種型別的內建資料型別;一種是 boolean 資料型別。boolean 資料型別是一種內建資料型別,用於定義帶有關鍵字 True 和 False 的表示式的真值和假值。
在 Python 中處理布林運算子或布林集合/陣列時,有很多情況需要對布林值取反並獲得與布林值相反的值。
本教程將演示在 Python 中否定布林值的不同方法。
在 Python 中使用 not 運算子計算否定布林值
Python 中的 not 運算子有助於返回給定布林值的負值或相反值。該運算子通過將 not 運算子放置為給定布林表示式的字首來使用。參考下面的示例。
a = 1
print(bool(a))
print(not a)
輸出:
True
False
這裡使用了 bool() 函式。它返回 Python 中給定變數的布林值,True 或 False。數字 0 和 1 的布林值在 Python 中預設設定為 False 和 True。
因此,在 1 上使用 not 運算子會返回 False,即 0。另外,請注意 not 運算子可用於 print 語句本身。
使用來自 operator 模組的 operator.not_() 函式來否定 Python 中的布林值
Python 中的 operator 模組用於提供與 Python 的內在運算子相關的各種函式。
operator.not_() 函式將一個布林值作為其引數,並返回該值的相反值。看看這裡的例子。
import operator
print(operator.not_(True))
輸出:
False
此函式還用於否定儲存在列表或陣列中的布林值。
import operator
bool_values = [True, True, False, True, False]
negate_bool = map(operator.not_, bool_values)
print(list(negate_bool))
輸出:
[False, False, True, False, True]
在上面的示例中,還使用了 map() 函式。此過程用於對定義的迭代器的所有項(例如列表、元組或字典)執行操作或應用函式。
在 Python 中使用~ 運算子來否定 NumPy 陣列的布林值
NumPy 陣列是具有預定義索引值的相同型別值的列表。NumPy 陣列的形狀由給出陣列大小的整數元組定義。
~ 運算子也稱為波浪號運算子。此運算子是按位求反運算子,它將數字作為二進位制數並將所有位轉換為相反的值。
例如,0 到 1 和 1 到 0。在 Python 中,1 表示 True,而 0 表示 False。因此,波浪號運算子將 True 轉換為 False,反之亦然。這是一個演示此過程的示例。
import numpy as np
b = np.array([True, True, False, True, False])
b = ~b
print(b)
輸出:
[False False True False True]
使用 NumPy 庫中的 bitwise_not() 函式來否定布林值
bitwise_not() 函式有助於將按位 NOT 操作分配給一個元素或一個元素陣列。
import numpy as np
b = np.array([True, True, False, True, False])
b = np.bitwise_not(b)
print(b)
輸出:
[False False True False True]
這裡使用了 NumPy 陣列,但也可以將單個布林值儲存在輸入變數中。
使用 NumPy 庫中的 invert() 函式來否定 Python 中的布林值
invert() 函式有助於按位反轉元素或元素陣列。此函式還返回按位 NOT 運算。
例子:
import numpy as np
b = np.array([True, True, False, True, False])
b = np.invert(b)
print(b)
輸出:
[False False True False True]
使用 NumPy 庫中的 logical_not() 函式來否定 Python 中的布林值
NumPy 庫的 logical_not() 函式基本上返回元素或元素陣列的 NOT 值的 True 值(逐元素)。
例子:
import numpy as np
b = np.array([True, True, False, True, False])
b = np.logical_not(b)
print(b)
輸出:
[False False True False True]
Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.
LinkedIn