问题
When I have to compare the contents of two array-like objects -- for instance list
s, tuple
s or collection.deque
s -- without regard for the type of the objects, I use
list(an_arrayish) == list(another_arrayish)
Is there any more idiomatic/faster/better way to achieve this?
回答1:
Compare it elementwise:
def compare(a,b):
if len(a) != len(b):
return False
return all(i == j for i,j in itertools.izip(a,b))
For Python 3.x, use zip
instead
回答2:
Tuples appear to be faster:
tuple(an_arrayish) == tuple(another_arrayish)
Here's a quick benchmark:
>>> timeit.Timer('list(a) == list(b)', 'a, b = (1, 2, 3, 4, 5), (1, 2, 3, 4, 6)').timeit()
2.563981056213379
>>> timeit.Timer('list(a) == list(b)', 'a, b = [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]').timeit()
2.4739551544189453
>>> timeit.Timer('tuple(a) == tuple(b)', 'a, b = (1, 2, 3, 4, 5), (1, 2, 3, 4, 6)').timeit()
1.3630101680755615
>>> timeit.Timer('tuple(a) == tuple(b)', 'a, b = [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]').timeit()
1.475499153137207
回答3:
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
Seeing that we're not running into the convention some other languages use of "equality here means we are testing if these references refer to the same object in memory" I'd say sticking with the ==
equality test is the simplest way to accomplish this and therefore the best.
来源:https://stackoverflow.com/questions/12135264/what-are-the-best-ways-to-compare-the-contents-of-two-list-like-objects