Alex Nikitin
Alex Nikitin

Reputation: 524

Filtering out shorter sublists

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

Answers (3)

Osman Mamun
Osman Mamun

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

user3483203
user3483203

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

niraj
niraj

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

Related Questions