If I have one long list: myList = [0,2,1,0,2,1]
that I split into two lists:
如果我有一个长列表:myList = [0,2,1,0,2,1]我将其拆分为两个列表:
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.
我已经看到问题要求通过对它们进行排序来比较两个列表,但在我的具体情况下,我没有检查排序比较,但是相同的列表比较。
3 个解决方案
#1
58
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.
如果同一索引处的元素相等,则列表相等。然后考虑订购。
#2
3
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
如果你只想检查它们是否相同,a == b应该给你真/假,并考虑到订购。
In case you want to compare elements, you can use numpy for comparison
如果您想比较元素,可以使用numpy进行比较
c = (numpy.array(a) == numpy.array(b))
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.
这里,c将包含一个包含3个元素的数组,所有这些元素都是正确的(对于您的示例)。如果a和b的元素不匹配,则c中的相应元素将为false。
#3
1
The expression a == b
should do the job.
表达式a == b应该完成这项工作。
#1
58
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.
如果同一索引处的元素相等,则列表相等。然后考虑订购。
#2
3
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
如果你只想检查它们是否相同,a == b应该给你真/假,并考虑到订购。
In case you want to compare elements, you can use numpy for comparison
如果您想比较元素,可以使用numpy进行比较
c = (numpy.array(a) == numpy.array(b))
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.
这里,c将包含一个包含3个元素的数组,所有这些元素都是正确的(对于您的示例)。如果a和b的元素不匹配,则c中的相应元素将为false。
#3
1
The expression a == b
should do the job.
表达式a == b应该完成这项工作。