簡體   English   中英

查找兩個不同大小的無序 Python 列表的匹配元素

[英]Find matching elements of two unordered Python lists of different sizes

我收到此錯誤: index out of range, in if largerList[j] == smallerList[i] 我正在做一個關於二叉搜索樹的作業,我把樹放到列表中,我只是想比較這兩個列表:

def matchList(largerList, smallerList) :
        matches = []
        for i in smallerList:
            for j in largerList:
                if largerList[j] == smallerList[i] :
                    matches[i] = smallerList[i]
        return matches

我假設嵌套的 for 循環應該完全迭代每個循環中的所有元素,所以smallerList是較小的列表,所以smallerList不會使largerList越界。 內部 for 循環應該完全遍歷所有較大的列表,將每個值與較小列表的每個元素進行比較。 為什么不起作用?

你不能設置一個列表值matches[i]如果該索引不存在中的matches

嘗試附加:

將這個matches[i] = smallerList[i]這個matches = matches.append(smallerList[i])

試圖在這樣的列表中找到匹配的元素是相當低效的。 您可以改進以使其更像 Pythonic 的一件事是使用列表理解:

matches = [i for i in largerList if i in smallerList]

但是在數學上更明智的方法仍然是意識到我們有兩組元素,我們想要找到兩組的交集,這樣我們就可以寫出類似的東西:

matches = set(largerList).intersection(smallerList)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM