Reputation: 3
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?
Upvotes: 0
Views: 113
Reputation: 7867
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
Upvotes: 1
Reputation: 7509
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).
Upvotes: 1