确定2个列表是否具有相同的元素,而与顺序无关?

编程入门 行业动态 更新时间:2024-10-27 20:31:09
本文介绍了确定2个列表是否具有相同的元素,而与顺序无关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

很抱歉,这个问题很简单,但是我很难找到答案.

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个列表是否具有相同的元素,而与顺序无关?

本文发布于:2023-11-05 16:03:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而与   顺序   元素   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!