如何比较python中的两个有序列表?


105

如果我有一个长长的清单:myList = [0,2,1,0,2,1]我分为两个清单:

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

我如何比较这两个列表以查看它们是否相等/相同,并约束它们必须处于相同顺序?

我看到过一些问题,要求通过对两个列表进行排序来进行比较,但是在我的特定情况下,我不是要检查排序的比较,而是要检查相同的列表比较。

Answers:


175

只需使用经典==运算符:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

如果相同索引处的元素相等,则列表相等。然后考虑订购。


3
这可能会返回以下错误,并带有一个numpy列表:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Alex Reynolds

@AlexReynolds说了什么。您必须使用all(arr1 == arr2)或进行测试(arr1 == arr2).all()
Julio

10

如果您只想检查它们是否相同,a == b则应在考虑订购的情况下为您提供对/错。

如果要比较元素,可以使用numpy进行比较

c = (numpy.array(a) == numpy.array(b))

在这里,c将包含一个包含3个元素的数组,所有元素均为true(对于您的示例)。如果a和b的元素不匹配,则c中的相应元素将为false。


然后检查c.all()是否为True
Pulkit Bansal

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.