Python – 如何检查两个列表是否反向相等
有时,在使用Python列表时,我们可能会遇到需要检查两个列表是否彼此相反的问题。这种问题可以在许多领域都有应用,例如日间编程和学校编程。让我们讨论可以执行此任务的某些方式。
Input : test_list1 = [5, 6, 7], test_list2 = [7, 6, 5]
Output : True
Input : test_list1 = [5, 6], test_list2 = [7, 6]
Output : False
方法 #1:使用reversed() and "==" operator
上述功能的组合可以用来解决这个问题。在此,我们使用 reversed() 执行反转任务并使用“==”运算符测试相等性。
# Python3 code to demonstrate working of
# Check if two lists are reverse equal
# Using reversed() + == operator
# initializing lists
test_list1 = [5, 6, 7, 8]
test_list2 = [8, 7, 6, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Check if two lists are reverse equal
# Using reversed() + == operator
res = test_list1 == list(reversed(test_list2))
# printing result
print("Are both list reverse of each other ? : " + str(res))
输出 :
The original list 1 : [5, 6, 7, 8]
The original list 2 : [8, 7, 6, 5]
Are both list reverse of each other ? : True
方法#2:使用列表切片+“==”运算符
这是解决此问题的另一种方法。在此,我们使用切片技术执行列表反转任务。
# Python3 code to demonstrate working of
# Check if two lists are reverse equal
# Using list slicing + "==" operator
# initializing lists
test_list1 = [5, 6, 7, 8]
test_list2 = [8, 7, 6, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Check if two lists are reverse equal
# Using list slicing + "==" operator
res = test_list1 == test_list2[::-1]
# printing result
print("Are both list reverse of each other ? : " + str(res))
输出 :
The original list 1 : [5, 6, 7, 8]
The original list 2 : [8, 7, 6, 5]
Are both list reverse of each other ? : True