如何比较python中的两个有序列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36420022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I compare two ordered lists in python?
提问by Jeremy
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.
我看到过要求通过排序来比较两个列表的问题,但在我的特定情况下,我不是在检查排序比较,而是检查相同的列表比较。
回答by Maxime Lorant
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.
如果相同索引处的元素相等,则列表相等。然后考虑排序。
回答by Vasanth
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。
回答by Abhiram
The expression a == b
should do the job.
表达式a == b
应该可以完成这项工作。