Search code examples
pythonpython-2.7listfrozenset

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].


Solution

  • 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]