The naive solution is to iterate over each pair, which is slow. However, you can do something like this:
- dict, ints ( ) , .
- , dict.
- 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]})
( , ). , , . , 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