本文主要记录在列表list的判断是否相等过程中遇到的问题,并对列表判断是否相等的相关知识进行汇总。
本文的原因是因为在判断列表list是否相等的过程中,关于==、is、operator.eq()三种方法存在疑惑,于是将这3种方法一并总结归纳如下。
用==操作判断列表是否相等的代码如下:
a = [1, 2, 'apple']
b = [1, 2, 'apple']
c = ['apple', 1, 2]
result_a_b = (a == b)
print("result_a_b = {}".format(result_a_b))
print("type(result_a_b) is {}".format(type(result_a_b)))
print("The result of a == b is : {}".format(a == b))
print("The result of a == c is : {}".format(a == c))
print("The result of b == c is : {}".format(b == c))
print('\n')
运行结果如下:
result_a_b = True
type(result_a_b) is <class 'bool'>
The result of a == b is : True
The result of a == c is : False
The result of b == c is : False
用is操作判断列表是否相等的代码如下:
a = [1, 2, 'apple']
b = [1, 2, 'apple']
c = ['apple', 1, 2]
d = a
print("The result of 'a is b' is : {}".format(a is b))
print("The result of 'a is c' is : {}".format(a is c))
print("The result of 'b is c' is : {}".format(b is c))
print("The result of 'a is d' is : {}".format(a is d))
print('\n')
运行结果如下:
The result of 'a is b' is : False
The result of 'a is c' is : False
The result of 'b is c' is : False
The result of 'a is d' is : True
用operator.eq()操作判断列表是否相等的代码如下:
from operator import *
x = [1, 2, 'apple']
y = [1, 2, 'apple']
z = ['apple', 1, 2]
result_x_y = eq(x, y)
print("The type of result_x_y is : {}".format(type(result_x_y)))
print("The result of eq(x,y) is : {}".format(eq(x, y)))
print("The result of eq(x,z) is : {}".format(eq(x, z)))
print("The result of eq(y,z) is : {}".format(eq(y, z)))
print('\n')
运行结果如下:
The type of result_x_y is : <class 'bool'>
The result of eq(x,y) is : True
The result of eq(x,z) is : False
The result of eq(y,z) is : False
在进行列表是否相等的判断时,直接采用operator.eq()函数的方法是最直接的。
Original: https://blog.csdn.net/weixin_43981621/article/details/124200061
Author: 我这一次
Title: Python中关于判断列表list是否相等的问题
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/671951/
转载文章受原作者版权保护。转载请注明原作者出处!