Reputation: 524
I have a nested list:
[['spam', 'eggs'],
['spam', 'eggs', '111'],
['spam', 'eggs', 'foo'],
['spam', 'eggs', '111', 'bar'],
['spam', 'eggs', 'foo', 'bar']]
What I need is an algorithm to get indexes of shorter sublists, all elements of which are contained in longer ones. In this example algorithm should return:
[0, 1, 2]
Any help would be appreciated!
Upvotes: 2
Views: 47
Reputation: 2882
out_index = [i for i in range(len(my_list))
if any(set(my_list[i]) < m
for m in [set(j) for j in my_list])]
Upvotes: 1
Reputation: 51155
You can convert each sublist to a set, and use the helpful issubset
method. This will not work if you have duplicate elements in your lists that you need to preserve.
x = [set(i) for i in x]
x = [i
for i, e in enumerate(x)
if any(e.issubset(j) and i != k
for k, j in enumerate(x))
]
# [0, 1, 2]
Upvotes: 1
Reputation: 18208
One way may be to use double for
loop in same list and check with .issubset
for those when not equal index
:
my_list = [['spam', 'eggs'],
['spam', 'eggs', '111'],
['spam', 'eggs', 'foo'],
['spam', 'eggs', '111', 'bar'],
['spam', 'eggs', 'foo', 'bar']]
indexes = []
for index1, item1 in enumerate(my_list):
for index2, item2 in enumerate(my_list):
if index1 != index2:
if set(item1).issubset(item2):
indexes.append(index1)
break
print(indexes)
Result:
[0, 1, 2]
Upvotes: 1