• 技术文章 >Python技术 >Python基础教程

    python如何比较两个list是否相同

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-10-10 11:11:35原创16267

    Python2可以使用cmp()函数来比较两个list是否相等。

    a=[1,-1,0]
    b=[1,-1,0]
    c=[-1,1,0]
    print cmp(a, b)
    print cmp(a, c)

    结果输出

    0
    1

    相关推荐:《Python基础教程

    cmp(list1 ,list2) ,

    当list1<list2会返回负数 -1、

    当list1>list2会返回正数 1、

    当list1=list2则返回0。

    list1=list2一定是两个列表必须完全相同(包括位置),只有这样才能是0。

    但是在Python3中我们可以使用operator方法来比较两个list是否相等。

    import operator
     
    a=[1,-1,0]
    b=[1,-1,0]
    c=[-1,1,0]
    print(operator.eq(a,b))
    print(operator.eq(a,c))

    实验结果:

    D:\pycharmprogram\leetcode\venv\Scripts\python.exe D:/pycharmprogram/leetcode/3Sum/operator_test.py
    True
    False
     
    Process finished with exit code 0

    分析:

    两个列表必须完全相同(包括位置),只有这样才能是True。

    专题推荐:python 比较 list
    上一篇:python xml解析中文乱码怎么办 下一篇:python 复数是什么意思

    相关文章推荐

    • python怎么比较两个字符串是否相等• python如何比较两个字符串是否相等• python比较字符串是否相等• python中怎么比较两个字符串是否相同

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网