0

Suppose I have a 2D list in python (the length of each list within is not the same, say the first list have 3 elements, but the second one has 4 elements). I have another 1D list with exactly 2 elements. I need to find the indices of the 2D list that contain both the elements of the 1D list (need not to be in sequence). I want to do this task very efficiently as it will be a part of a huge analysis task (not using loops especially).

For example:

2D list: [[4, 0, 2], [0, 3, 2], [3, 0, 4], [5, 3, 4], [3, 5, 6], [8, 1, 2], [7, 3, 6], [1, 7, 6], [8, 7, 1], [2, 3, 7, 8]]

1D list: [3, 4]

output: 2, 3

It is not essential that I use the list structure, is there any other structure in python that I can do it more efficiently?

rdas
  • 20,604
  • 6
  • 33
  • 46
A Sanjana
  • 3
  • 1

2 Answers2

1

Not sure about efficiency, but this is the list comprehension that gets the result you want:

>>> list2d = [[4, 0, 2], [0, 3, 2], [3, 0, 4], [5, 3, 4], [3, 5, 6], [8, 1, 2], [7, 3, 6], [1, 7, 6], [8, 7, 1], [2, 3, 7, 8]]
>>> list1d = [3, 4]
>>> result = [list2d.index(sublist) for sublist in list2d if all(value in sublist for value in list1d)]
>>> result
[2, 3]

Note that list comprehensions tend to perform better than using Python's map/filter operations, at least when there are lambda functions involved (which would be likely in your case).

jfaccioni
  • 7,099
  • 1
  • 9
  • 25
1

If your 1D list and your sublists are instead sets, you can

list2d = [
    {0, 2, 4}, {0, 2, 3}, {0, 3, 4}, {3, 4, 5}, {3, 5, 6},
    {8, 1, 2}, {3, 6, 7}, {1, 6, 7}, {8, 1, 7}, {8, 2, 3, 7}
]
set1d = {3, 4}

i = 0
res = set()
for s in list2d:
    if set1d <= s:
        res.add(i)
    i += 1

I'd very tentatively guess that's the fastest one can achieve in pure python

joel
  • 6,359
  • 2
  • 30
  • 55
  • Upvoted because this answer is probably faster than mine (although it requires the list -> set conversion first). – jfaccioni Jun 01 '19 at 21:09
  • @jfaccioni thanks. yeah mine's probably only faster if the data's already in that format – joel Jun 01 '19 at 21:23