天真的解決方案是在循環的每對,這是緩慢的。但是,你可以做一些沿的臺詞:
- 創建一個字典,將映射整數(在你的嵌套列表元素)包含列表的指數在你的主人名單。
- 循環遍歷主列表,併爲每個子列表添加索引到與dict中每個元素相對應的位置。
- 現在,字典的值由兩個元素爲「對」的列表組成。
這就是我的意思是:
>>> mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
>>>
>>> pairs = dict()
>>>
>>>
>>> from collections import defaultdict
>>>
>>> pairs = defaultdict(list)
>>>
>>> for idx, sub in enumerate(mylist):
... for a in sub:
... pairs[a].append(idx)
...
>>> pairs
defaultdict(<type 'list'>, {65: [5], 3: [4], 13: [3], 14: [1], 15: [0, 1], 19: [2, 5, 6], 20: [2, 6], 31: [6]})
你可以只用1元無視值列表(因爲那意味着我們沒有一對)。帶有2+元素的元素形成各種配對。例如與19
我們有[2, 5, 6]
含義:
你有。這種方法對於嵌套列表中的項目總數是線性的。如果您在嵌套列表長度上有一個合理的上限,那麼這是主列表大小中的O(n)。
現在的輸出:
>>> from itertools import combinations
>>>
>>> for k,v in pairs.iteritems():
... if len(v) > 1:
... for a,b in combinations(v, 2):
... print "Index {} matched with index {} for value {}".format(a, b, k)
...
Index 0 matched with index 1 for value 15
Index 2 matched with index 5 for value 19
Index 2 matched with index 6 for value 19
Index 5 matched with index 6 for value 19
Index 2 matched with index 6 for value 20
@kroolik,感謝您的快速回復。我想也許我應該將列表中的每個元素轉換爲一個集合。然後使用相交來比較每個集合。如果有匹配的值,那麼我會打印匹配值和它匹配的索引。你對這種方法有什麼看法?我遠嗎?或關閉?謝謝你的幫助。 – noahandthewhale
@kroolik,或許這可能對我有幫助? http://stackoverflow.com/questions/16603282/how-to-compare-each-item-in-a-list-with-the-rest-only-once – noahandthewhale
你可以嘗試@arshajii的解決方案 - 非常有效,易於實現,並且非常直接瞭解。 –