如何有效地比较 Python 中的两个无序列表(不是集合)? [英] How to efficiently compare two unordered lists (not sets) in Python?

查看:31
本文介绍了如何有效地比较 Python 中的两个无序列表(不是集合)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]

一个&b 应该被认为是相等的,因为它们具有完全相同的元素,只是顺序不同.

a & b should be considered equal, because they have exactly the same elements, only in different order.

问题是,我的实际列表将由对象(我的类实例)组成,而不是整数.

The thing is, my actual lists will consist of objects (my class instances), not integers.

推荐答案

O(n):Counter() 方法是最好的(如果你的对象是可散列的):

O(n): The Counter() method is best (if your objects are hashable):

def compare(s, t):
    return Counter(s) == Counter(t)

O(n log n):sorted() 方法次之(如果您的对象是可排序的):

O(n log n): The sorted() method is next best (if your objects are orderable):

def compare(s, t):
    return sorted(s) == sorted(t)

O(n * n):如果对象既不是可散列的,也不是可排序的,则可以使用相等:

O(n * n): If the objects are neither hashable, nor orderable, you can use equality:

def compare(s, t):
    t = list(t)   # make a mutable copy
    try:
        for elem in s:
            t.remove(elem)
    except ValueError:
        return False
    return not t

这篇关于如何有效地比较 Python 中的两个无序列表(不是集合)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆