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
.
When comparing a
to c
, should return False
: there are items in a
that don't exist on c
.
What is the pythonic way to do it?
排序,然后比较。
sorted(a) == sorted(b)
Use sets or 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.
Use set
s:
In [4]: set(a) == set(b)
Out[4]: True
In [5]: set(a) == set(c)
Out[5]: False
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.