你不需要这个功能_matching_lists
,因为你可以使用==
:
>>> [1,2,3] == [1,2,3]
True
>>> [1,2,3] == [3,1,2]
False
我建议使用any() http://docs.python.org/3/library/functions.html#any找到匹配项后立即返回,并使用生成器表达式来避免在内存中构造旋转列表:
def _compare_rotated_lists(a, b):
"""Return `True` if the list `a` is equal to a rotation of the list `b`."""
return any(a == b[i:] + b[:i] for i in range(len(b)))
您可能会考虑检查列表的长度是否相同,以快速拒绝简单的情况。
return len(a) == len(b) and any(a == b[i:] + b[:i] for i in range(len(b)))
正如评论中所讨论的,如果您知道a
and b
是可散列的,您可以使用进行初始比较collections.Counter http://docs.python.org/3/library/collections.html#collections.Counter:
return Counter(a) == Counter(b) and any(a == b[i:] + b[:i] for i in range(len(b)))
如果你知道a
and b
具有可比性,您可以使用以下方法进行初步比较sorted
:
return sorted(a) == sorted(b) and any(a == b[i:] + b[:i] for i in range(len(b)))