Python中关于判断列表list是否相等的问题

Python中关于判断列表list是否相等的问题

    本文主要记录在列表list的判断是否相等过程中遇到的问题,并对列表判断是否相等的相关知识进行汇总。

目录

  • Python中关于判断列表list是否相等的问题
  • 0.问题起源
  • 1.用==操作判断列表是否相等
  • 2.用is操作判断列表是否相等
  • 3.用operator.eq()操作判断列表是否相等
  • 4.小结
  • 0.问题起源

        本文的原因是因为在判断列表list是否相等的过程中,关于==、is、operator.eq()三种方法存在疑惑,于是将这3种方法一并总结归纳如下。

    1.用==操作判断列表是否相等

        用==操作判断列表是否相等的代码如下:

    # 1.使用 == 判断两个列表是否相同
    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
    

    2.用is操作判断列表是否相等

        用is操作判断列表是否相等的代码如下:

    # 2.使用 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))   # 因为列表d是列表a的简单赋值操作,所以是相等的
    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
    

        其中关于赋值、浅拷贝、深拷贝的概念,可以参考博文:Python中关于列表list的赋值问题

    3.用operator.eq()操作判断列表是否相等

        用operator.eq()操作判断列表是否相等的代码如下:

    
    # 3.使用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
    

    4.小结

        在进行列表是否相等的判断时,直接采用operator.eq()函数的方法是最直接的。

    来源:我这一次

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python中关于判断列表list是否相等的问题

    发表评论