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

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

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。

相关推荐
小小测试开发1 天前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想1 天前
Python 中的装饰器
python·装饰器
我叫唧唧波1 天前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)1 天前
【无标题】
开发语言·c#
copyer_xyf1 天前
Python 异常处理
前端·后端·python
XBodhi.1 天前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧1 天前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy1 天前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.1 天前
【01】Python 机器学习
开发语言·python
为爱停留1 天前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python