如何高效比较两个无序列表(而不是集合)?

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

考虑到a和b具有完全相同的元素,只是顺序不同,因此应被视为相等。

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


8
物体是如何进行比较的? - Marcelo Cantos
2
真实列表的预期大小是多少?将要比较的列表大小是否相当或非常不同?您是否预计大多数列表将匹配还是不匹配? - Dmitry B.
可以先检查 len() - greybeard
12个回答

0

插入这个:

def lists_equal(l1: list, l2: list) -> bool:
    """

    import collections
    compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
    ref:
        - https://dev59.com/l2kw5IYBdhLWcg3w1d4m
        - https://dev59.com/Umsz5IYBdhLWcg3wiYY0
    """
    compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
    set_comp = set(l1) == set(l2)  # removes duplicates, so returns true when not sometimes :(
    multiset_comp = compare(l1, l2)  # approximates multiset
    return set_comp and multiset_comp  #set_comp is gere in case the compare function doesn't work

0

你可以编写自己的函数来比较这些列表。

我们拿到两个列表。

list_1=['John', 'Doe'] 
list_2=['Doe','Joe']

首先,我们定义一个空字典,计算列表项并写入字典中。
def count_list(list_items):
    empty_dict={}
    for list_item in list_items:
        list_item=list_item.strip()
        if list_item not in empty_dict:
            empty_dict[list_item]=1
        else:
            empty_dict[list_item]+=1
    return empty_dict


        

之后,我们将通过使用以下函数来比较两个列表。
def compare_list(list_1, list_2):
    if count_list(list_1)==count_list(list_2):
        return True
    return False
compare_list(list_1,list_2)

抱歉,我错误地键入了 empty_dict 变量的名称。我已经更正了它。感谢您的反馈! - Şahin Murat Oğur
如果compare_list()只是读取return count_list(list_1)==count_list(list_2),会怎样呢? - greybeard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接