python - Identifying sublists entirely contained within other lists -
i find sublist within list matches list, , create new list:
so this:
lista = [["a", "b", "c"],["d", "e", "f"]] listb = ["b", "c", "d", "e", "f"] to generate this:
newvariable = ["d", "e", "f"] because a, b, c not contained in listb, d, e, f is.
i have tried loops all() can't seem make them work?
any ideas? i'm guessing simple i'm missing.
the straight forward solution
>>> lista = [["a", "b", "c"],["d", "e", "f"]] >>> listb = ["b", "c", "d", "e", "f"] >>> set_b = set(listb) >>> >>> [l l in lista if all(x in set_b x in l)] [['d', 'e', 'f']] which gives list lists lista contained in listb.
note instead of using listb actual containment checks using set set_b sets have o(1) membership checks. (otherwise, above all-checks have quadratic runtime.)
i assumed order of elements in listb not matter. if does, please clarify.
Comments
Post a Comment