[英]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.