开发者

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.

When comparing a to c, should return False: there are items in a that don't exist on c.

What is the pythonic way t开发者_JS百科o do it?


Sort, then compare.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜