[英]How can I compare two lists in python, and return that the second need to have the same values regardless of order?
a = [1, 2, 3, 4]
b = [2, 4, 3, 1]
c = [2, 3]
When comparing a to b, should return True
: all items in a
are presented in b
, and all items in b
are presented in a
. 当比较A到B,应该返回True
:在所有项目a
都在呈现b
,并在所有项目b
都在呈现a
。
When comparing a
to c
, should return False
: there are items in a
that don't exist on c
. 当比较a
到c
,应该返回False
:有在项目a
不上存在c
。
What is the pythonic way to do it? 什么是pythonic方式呢?
排序,然后比较。
sorted(a) == sorted(b)
Use sets or frozensets. 使用集合或frozensets。
set_a = {1, 2, 3, 4} #python 2.7 or higher set literal, use the set(iter) syntax for older versions
set_b = {2, 4, 4, 1}
set_a == set_b
set_a - set_b == set_b - set_a
The biggest advantage of using sets over any list method is that it's highly readable, you haven't mutated your original iterable, it can perform well even in cases where a is huge and b is tiny (checking whether a and b have the same length first is a good optimization if you expect this case often, though), and using the right data structure for the job is pythonic. 使用集合优于任何列表方法的最大优点是它具有高可读性,您没有改变原始可迭代,即使在a很大且b很小的情况下它也可以很好地执行(检查a和b是否具有相同的长度)首先是一个很好的优化,如果你经常期望这种情况,并且使用正确的数据结构是pythonic。
Turn them into sets: 把它们变成几组:
>>> set([1,2,3,4]) == set([2,4,3,1])
True
>>> set([2, 3]) == set([1,2,3,4])
False
If your lists contain duplicate items, you'll have to compare their lengths too. 如果您的列表包含重复项,则您还必须比较它们的长度。 Sets collapse duplicates. 设置折叠重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.