Python – 列表元素間的按位或運算


簡介

Python 語言屬於面向物件程式設計 (OOP) 概念,它會在不檢查錯誤的情況下立即執行程式碼。這種語言由 Guido Rossum 於 1989 年發明,並於 1991 年在全球釋出。Python 是一種用途廣泛的高階語言,使用者可以輕鬆理解。在當今世界,對於擁有大量資料的組織來說,資料處理是最具挑戰性的任務之一,而隨著資料科學和機器學習的發展,資料訪問變得更加容易。

列表元素間的按位或運算

用於表示按位或運算子的運算子是“|”。按位或也可以使用 union() 函式定義為集合並集。按位或運算子的示例如下所示,其中包含兩個變數:

A = [2, 4, 6, 9]
B = [3, 6, 7]

上述元素可以透過兩種方式進行按位或運算:

情況 1

result= A|B

情況 2

result = B.union(A)

方法

方法 1 - 使用迭代方法

方法 2 - 使用 lambda 方法

方法 3 - 使用 numpy 模組

方法 1:使用迭代方法進行 Python 列表元素間的按位或運算

演算法

  • 步驟 1 - 使用三個整型元素 40、50 和 90 初始化列表資料結構。

  • 步驟 2 - 將 out 變數賦值為“0boo”,它在十進位制中等於 0。

  • 步驟 3 - 列表的每個元素都執行按位或運算。

  • 步驟 4 - 將 out 的當前值和 list_1 的當前元素進行比較,並將結果儲存在名為“out”的變數中。

  • 步驟 5 - 然後,print 語句將返回執行按位或運算子後的值。

示例

#initializing the list with three integer elements
list_1=[40,50,90]
#the output is assigned a "0" decimal value
out=0b00
#for loop is used to iterate through the list using range() and length of the list
for a in range(len(list_1)):
   #list returns bitwise OR operator of the list
   out|=list_1[a]

#it returns the value after performing bitwise OR operator
print("List after performing the operation",out)

輸出

List after performing the operation 122

方法 2:使用 lambda 函式進行 Python 列表元素間的按位或運算

演算法

  • 步驟 1 - 匯入所需的模組以使用 reduce() 函式。

  • 步驟 2 - 使用三個整型元素 40、50 和 90 定義列表資料結構。

  • 步驟 3 - 使用符號“|”使用 lambda 函式執行按位或運算。

  • 步驟 4 - 為此,使用 key 引數,然後 lambda 函式使用 reduce 函式來獲取結果。

  • 步驟 5 - 然後,print 語句將返回執行按位或運算子後的值,以二進位制格式和十進位制格式兩種形式顯示。

示例

#importing the functools module to use the reduce function
from functools import reduce

#initializing the list with three integer elements
list_1 = [40, 50, 90]

#lambda function is used to find the bitwise OR with the key parameter
#after generating the result, it is reduced using the reduce() function and stored in out variable
result = reduce(lambda a, b: a | b, list_1)
#it returns the value after performing bitwise OR operator
print("The Bitwise OR operator of the given list in binary:",bin(result))

print("The Bitwise OR operator of the given list :",result)

輸出

The Bitwise OR operator of the given list in binary: 0b1111010
The Bitwise OR operator of the given list : 122

方法 3:使用 numpy 模組進行 Python 列表元素間的按位或運算

演算法

  • 步驟 1 - 匯入所需的模組以使用“np”函式。

  • 步驟 2 - 使用三個整型元素 40、50 和 90 初始化列表資料結構。

  • 步驟 3 - 使用名為“np.bitwise_or.reduce()”的函式對列表的所有元素執行按位或運算。

  • 步驟 4 - 然後,print 語句將返回執行按位或運算子後的值(十進位制格式)。

#importing the numpy module to use the "np" function
import numpy as np

#initializing the list with three integer elements
list_1 = [40, 50, 90]

#direct function to add the elements of the list is done
result = np.bitwise_or.reduce(list_1)

#it returns the value after performing bitwise OR operator
print("List after performing the operation", result)

輸出

List after performing the operation 122

結論

本文描述了三種執行按位或運算的方法。在第一種方法中,使用 for 迴圈和 range() 和 len() 方法迭代列表的元素。在第二種方法中,lambda 函式與 reduce() 函式一起使用。當函式未定義或未知時,lambda 函式可以高效地使用。在最後一種方法中,匯入 numpy 模組以使用“np”函式執行按位或運算。

更新於:2023年8月25日

瀏覽量:354

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告