Check item membership in set in Python -


hello i've been coding couple of months , know basics, i'm having set membership problem can't find solution.

i have list of lists of pairs of integers, , want remove list have "a" integer in them. thought using sets easiest way. bellow code:

## item test against.  = set([3])  ## list test.       groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]       ## list contain lists present ## in groups not contain "a" groups_no_a = []          group in groups:     group = set(group)     if in group:         groups_no_a.append(group)     ## thought problem had     ## clearing variable put in,        ## no remedy.      group.clear()     print groups_no_a  

i had tried using s.issubset(t) until realized tested if every element in s in t.

thank you!

you want test if there no intersection:

if not & group: 

or

if not a.intersection(group): 

or, inversely, sets disjoint:

if a.isdisjoint(group): 

the method forms take any iterable, don't have turn group set that. following one-liner work too:

groups_no_a = [group group in groups if a.isdisjoint(group)] 

demo:

>>> = set([3])  >>> groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]      >>> [group group in groups if a.isdisjoint(group)] [[1, 2], [5, 4]] 

if testing one element, creating sets going cost more in performance gain in testing membership, , doing:

3 not in group 

where group short list.

you can use timeit module compare pieces of python code see works best specific typical list sizes.


Popular posts from this blog

Apache NiFi ExecuteScript: Groovy script to replace Json values via a mapping file -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -