Sayan Basu
Sayan Basu

Reputation: 43

Check to see if frozen set is a subset of list and the index of every element that is a subset

I have a bunch of frozensets and they are all subsets of a list. What I want to find out is the position of each element of the frozen set in the list.

for e.g.:

a = frozenset([1])
b = frozenset([2, 3])
l = [1, 2, 3, 4]

Now I already know the frozensets are a subset of the list l.

What I want is the index position of items in the list i.e. when I am checking for a, the function should return the index position for 1 in the list l i.e. [0].

Similarly for b, it should first return [1, 2].

Upvotes: 0

Views: 1707

Answers (2)

Dan D.
Dan D.

Reputation: 74655

If l is constant and its items are hashable (they have to be if they are members of a set), then why not make an index:

idx = {v:i for i,v in enumerate(l)}

This might have problems if l has duplicates (len(l)!=len(set(l))).

then the function that returns the set of indexes from the set of values is:

def indexes(S):
    return set(idx[v] for v in S)

This returns a set rather than a list because the order of the set S is undefined so the order of the list of indexes is also undefined so rather than use a list and imply an order that does not exist, use a set.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122222

If you already know a and b are subsets, just use a list comprehension to gather indices of values that are members; use the enumerate() function to supply the indices:

result = [i for i, v in enumerate(l) if v in subset]

where subset is one of your frozenset instances.

Demo:

>>> a = frozenset([1])
>>> b = frozenset([2, 3])
>>> l = [1, 2, 3, 4]
>>> [i for i, v in enumerate(l) if v in a]
[0]
>>> [i for i, v in enumerate(l) if v in b]
[1, 2]

Upvotes: 2

Related Questions