Python – 列表元素之间的按位或运算

Python – 列表元素之间的按位或运算

介绍

Python语言属于面向对象编程概念,并且它会立即运行代码而不检查错误。这种语言由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:Python – 使用lambda函数对列表元素进行按位或运算

算法

  • 步骤1 - 导入所需的模块以使用reduce()函数。

  • 步骤2 - 使用三个整数元素40、50和90定义列表数据结构。

  • 步骤3 - 使用lambda函数使用符号“|”执行按位或操作。

  • 步骤4 - 为此使用了关键参数,然后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:Python – 使用numpy模块对列表元素进行位或运算

算法

  • 步骤1 - 导入所需的模块以使用”np”函数。

  • 步骤2 - 使用三个整数元素40、50和90初始化列表数据结构。

  • 步骤3 - 使用名为”np.bitwise_or.reduce()”的函数对列表的所有元素执行位或操作。

  • 步骤4 - 然后将打印语句返回经过位或操作后的十进制格式的值。

#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函数执行位或操作。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程