📜  Python|列出反转

📅  最后修改于: 2022-05-13 01:55:09.152000             🧑  作者: Mango

Python|列出反转

有时,在编程时,我们可能需要在列表元素之间执行某些按位运算。这是一个必不可少的实用程序,因为我们多次遇到按位运算。让我们讨论可以执行此任务的某些方式。

方法 #1:使用map() + lambda + "~" operator
可以组合上述功能来执行此任务。我们可以使用 map() 来累积由 lambda函数指定的反转逻辑的结果。

# Python3 code to demonstrate working of
# List Inversions
# Using map() + lambda + "~" operator
  
# initializing list
test_list = [7, 8, 9, 1, 10, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List Inversions
# Using map() + lambda + "~" operator
res = list(map(lambda x: ~x, test_list)) 
  
# printing result 
print("The Bitwise Inversions of list elements are : " + str(res))
输出 :
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise Inversions of list elements are : [-8, -9, -10, -2, -11, -8]

方法 #2:使用map() + operator.invert
也可以使用此方法执行此任务。在这种情况下,上述方法中由 lambda函数执行的任务是使用 ior函数执行累积反转操作。

# Python 3 code to demonstrate working of
# List Inversions
# Using map() + operator.invert
from operator import invert
  
# initializing list
test_list = [7, 8, 9, 1, 10, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List Inversions
# Using map() + operator.invert
res = list(map(invert, test_list))
  
# printing result 
print("The Bitwise Inversions of list elements are : " + str(res))
输出 :
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise Inversions of list elements are : [-8, -9, -10, -2, -11, -8]