[譯]在python中如何有效的比較兩個無序的列表是否包含完全同樣的元素(不是set)?


原文來源: https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets-in-python

問:

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

我們需要判斷a和b是相等的,因為他們有同樣的元素,盡管他們的順序不同。
但是實際情況是,list會按照順序比對內部元素,該如何解決?

答:
O(n)復雜度: 如果內部的對象是可hash的,那么Collections下的Counter方法是最好的。

from collections import Counter
def compare(s, t):
    return Counter(s) == Counter(t)

O(nlogn)復雜度:如果對象可以排序,那么sorted()方法是次優的。

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

O(n*n)復雜度:如果對象既不可以hash又無法排序,我們可以使用以下方法:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM