有没有办法在python中查看两个列表是否完全相同而没有循环?

时间:2022-10-17 14:01:04

Say I have:

说我有:

a = [1, 2, 3]
b = [1, 2, 3]

is there a way to test the lists to see if they are the same, without having to loop through each entry?

有没有办法测试列表,看看它们是否相同,而不必遍历每个条目?

Here's what I was thinking..I know to check if two variables are the same I could use:

这就是我的想法..我知道检查两个变量是否相同我可以使用:

id(a)

but it doesn't work because the ID's are different so is there some type of checksum or way that python stores values of the table so I can simply compare two variables?

但它不起作用,因为ID是不同的,所以有一些类型的校验和或python存储表的值的方式所以我可以简单地比较两个变量?

3 个解决方案

#1


11  

Doesn't == work?

不= =工作?

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True

#2


3  

the == operator should function as expected on lists

==运算符应该在列表上按预期运行

>>> x = [1, 2]  
>>> y = [1, 2]
>>> x == y
True

#3


0  

the == operator should function works on lists

==运算符应该在列表上起作用

This output is received on certain versions of python, I don't know which.

这个输出是在某些版本的python上收到的,我不知道哪个。

>>> import numpy as np
>>> x = [1, 2, 3, 4]  
>>> y = [1, 2, 3, 4]
>>> z = [1, 2, 2, 4]
>>> x == y
[True, True, True, True]
>>> x == z
[True, True, False, True]

After this, just use numpy to determine the entire list.

在此之后,只需使用numpy来确定整个列表。

>>> np.all(x == y)
True
>>> np.all(x == z)
False

or if only a single similarity is required:

或者如果只需要一个相似性:

>>> np.any(x == z)
True

#1


11  

Doesn't == work?

不= =工作?

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True

#2


3  

the == operator should function as expected on lists

==运算符应该在列表上按预期运行

>>> x = [1, 2]  
>>> y = [1, 2]
>>> x == y
True

#3


0  

the == operator should function works on lists

==运算符应该在列表上起作用

This output is received on certain versions of python, I don't know which.

这个输出是在某些版本的python上收到的,我不知道哪个。

>>> import numpy as np
>>> x = [1, 2, 3, 4]  
>>> y = [1, 2, 3, 4]
>>> z = [1, 2, 2, 4]
>>> x == y
[True, True, True, True]
>>> x == z
[True, True, False, True]

After this, just use numpy to determine the entire list.

在此之后,只需使用numpy来确定整个列表。

>>> np.all(x == y)
True
>>> np.all(x == z)
False

or if only a single similarity is required:

或者如果只需要一个相似性:

>>> np.any(x == z)
True