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

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

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

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

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

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

If I have one long list: myList = [0,2,1,0,2,1] that I split into two lists:

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

how can I compare these two lists to see if they are both equal/identical, with the constraint that they have to be in the same order?

I have seen questions asking to compare two lists by sorting them, but in my specific case, I am not checking for a sorted comparison, but identical list comparison.


回答 0

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

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

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

Just use the classic == operator:

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

Lists are equal if elements at the same index are equal. Ordering is taken into account then.


回答 1

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

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

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

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

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

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

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don’t match, then the corresponding elements in c will be false.


回答 2

表达式a == b应该可以完成工作。

The expression a == b should do the job.