What are the best ways to compare the contents of two list-like objects?

橙三吉。 提交于 2019-12-23 09:38:18

问题


When I have to compare the contents of two array-like objects -- for instance lists, tuples or collection.deques -- 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!