ITPub博客

首页 > IT职业 > IT职场 > python如何比较两个list是否相同

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

IT职场 作者:zhjhome 时间:2021-09-11 10:30:42 0 删除 编辑

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:pycharmprogramleetcodevenvScriptspython.exe D:/pycharmprogram/leetcode/3Sum/operator_test.py
True
False
 
Process finished with exit code 0

分析:

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2530/viewspace-2836115/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    102
  • 访问量
    948