-3

I have a list of lists:

[[10, 9, 8], [8, 7], [1, 2, 3]]

The sublists are not necessarily of the same size. I need to find a number that occurs in two seperate lists, and return the list index and the numbers index in those lists.

in this case it would be 8, list 0, list 1, list 0 idx 2, list 1 idx 0.

Right now I am doing it with a bunch of for loops, but this is ridiculously slow... are there are faster more pythonic way of achieving this?

NicolaiF
  • 1,283
  • 1
  • 20
  • 44
  • what is there would be more than one common value between lists? `[[10, 9, 8], [8, 7, 3], [1, 2, 3, 9]]` – RomanPerekhrest Jun 01 '18 at 16:03
  • Your question is vague thus you probably won't get the desired answers. Please try to add more clear requirements for the algorithm. – Amr Keleg Jun 01 '18 at 16:09
  • 1
    Exactly 2? Or at least 2? – user3483203 Jun 01 '18 at 16:11
  • Just need to match two lists, then idealy terminate after matching two list – NicolaiF Jun 01 '18 at 16:16
  • More than one common element is fine, just return one of them – NicolaiF Jun 01 '18 at 16:17
  • @Prune I don't just want to dupe-hammer it open again, but I don't think it's a dupe (at least not of that question), since OP specifically is looking for the indices of the duplicate elements, and `set.intersection` won't be much help in this case. – tobias_k Jun 02 '18 at 14:56
  • The problem is entirely different from the one linked in the duplicate post... as Tobias is stating. – NicolaiF Jun 02 '18 at 14:58

2 Answers2

3

You can enumerate the lists and items in the list and store the index-tuples for each element in a dict, then filter those entries that have more than two occurrences.

lst = [[10, 9, 8], [8, 7], [1, 2, 3]]
in_list = collections.defaultdict(list)
for i, x in enumerate(lst):
    for k, y in enumerate(x):
        in_list[y].append((i, k))

res = {k: v for k, v in in_list.items() if len(v) > 1}
# {8: [(0, 2), (1, 0)]}

(This assumes that no element appears more than once in the same sublist.)

While this also uses "a bunch of for loop" (depending on your definition of "a bunch"), it will visit every element in the nested list only exactly once, giving it O(n) (n = comb. size of lists).

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0
from itertools import combinations
search = list(combinations(range(len(solutions)), 2))

for i in search:
    res = list(set(solutions[i[0]]) & set(solutions[i[1]]))
    if len(res) != 0:
        save = [i, res[0]]

idxList1 = solutions[save[0][0]].index(save[1])
idxList2 = solutions[save[0][1]].index(save[1])

This does what it is supposed to, but it seems like a poor solution.

NicolaiF
  • 1,283
  • 1
  • 20
  • 44