很抱歉,这个问题很简单,但是我很难找到答案.
Sorry for the simple question, but I'm having a hard time finding the answer.
比较2个列表时,我想知道它们是否相等",因为它们具有相同的内容,但顺序不同.
When I compare 2 lists, I want to know if they are "equal" in that they have the same contents, but in different order.
例如:
x = ['a', 'b'] y = ['b', 'a']我希望x == y的评估结果为True.
推荐答案您只需检查带有x和y元素的多集是否相等:
You can simply check whether the multisets with the elements of x and y are equal:
import collections collections.Counter(x) == collections.Counter(y)这要求元素是可哈希的;运行时将位于O(n)中,其中n是列表的大小.
This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.
如果元素也是唯一的,则还可以转换为集合(相同的渐近运行时,实际上可能会快一点):
If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):
set(x) == set(y)如果元素不是可哈希的,而是可排序的,则另一个选择(O(n log n)中的运行时)是
If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is
sorted(x) == sorted(y)如果元素既不可散列也不可排序,则可以使用以下帮助函数.请注意,这将非常慢(O(n²)),并且通常在不可散列和不可排序元素的神秘案例之外使用 .
If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.
def equal_ignore_order(a, b): """ Use only when elements are neither hashable nor sortable! """ unmatched = list(b) for element in a: try: unmatched.remove(element) except ValueError: return False return not unmatched更多推荐
确定2个列表是否具有相同的元素,而与顺序无关?
发布评论