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。

相关推荐
u***32432 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计5 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95275 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z5 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
9***P3345 小时前
PHP代码覆盖率
开发语言·php·代码覆盖率
daidaidaiyu6 小时前
一文入门 LangGraph 开发
python·ai
CoderYanger6 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz6 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
多多*6 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
p***43486 小时前
Rust网络编程模型
开发语言·网络·rust