简体   繁体   中英

Efficient list comparison in python

I'd like to efficiently compare two lists and determine if both share exactly the same elements.

The lists can be None , empty and of various lengths. Ordering of the elements inside the list does not matter, so ['a', 'b', 'c'] == ['a', 'c', 'b'] are equal in my case.

My current solution looks like this:

 def list_a_equals_list_b(list_a, list_b):
    if list_a != None and list_b != None:
        if len(list_a) != len(list_b):
            return False
        else:
            return len(frozenset(list_a).intersection(list_b)) == len(list_a)
    elif list_a == None and list_b == None:
        return True
    else:
        return False

Is there a more efficient way to compare those lists?

Thanks!

If you don't have duplicates in either lists you can use a set:

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and not set(listA).symmetric_difference(listB):
   # lists have the same elements
else:
   # there are differences

If you do allow duplicates, then yo can use Counter from collections (which would also work if you don't have duplicates)

from collections import Counter

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and Counter(listA)==Counter(listB):
   # lists have the same elements
else:
   # there are differences

The Counter() method is best if your objects are hashable. but here sorted() built-in function is your best option.

def list_a_equals_list_b(list_a, list_b):
    return (list_a == None and list_b == None) or sorted(list_a) == sorted(list_b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM