Best way to check if a collection contains only items in another collection?

What is the best way to check if an array / tuple / list only contains items in another array / tuple / list?

I tried the following 2 approaches which are better / more pythonic for different kinds of collections? What other (best) methods can be used for this test?

import numpy as np

input = np.array([0, 1, -1, 0, 1, 0, 0, 1])
bits = np.array([0, 1, -1])

# Using numpy
a=np.concatenate([np.where(input==bit)[0] for bit in bits])
if len(a)==len(input):
    print 'Valid input'

# Using sets
if not set(input)-set(bits):
    print 'Valid input'
+3
source share
3 answers

Your # Using numpyone of them is terribly inefficient for large sets as it creates a whole copy of your input list.

I would probably do:

if all(i in bits for i in input):
    print 'Valid input'

, , , list ( set), , ( False) input, bits.

+4

numpy, in1d:

>>> import numpy as np
>>> 
>>> input = np.array([0, 1, -1, 0, 1, 0, 0, 1])
>>> bits = np.array([0, 1, -1])
>>> 
>>> if np.in1d(input, bits).all():
...     print 'Valid input'
... 
Valid input
+5

As a rule, you just use this method, it can be faster than recounting a new set using the operator -:

input = set([0, 1, -1, 0, 1, 0, 0, 1])
bits = set([0, 1, -1])

input.issubset(bits)

EDIT:

issubset is a method written specifically for this problem (see source http://hg.python.org/releasing/2.7.3/file/7bb96963d067/Objects/setobject.c ). This is basically equivalent to:

def issubset(self, other):
    if len(self) > len(other):
        return False

    for i in self:
        if i not in other:
            return False

    return True
+2
source

All Articles