检查集合是否仅包含其他集合中的元素的最佳方法是什么?

Dha*_*ara 3 python

检查数组/元组/列表是否只包含另一个数组/元组/列表中的元素的最佳方法是什么?

我尝试了以下两种方法,对于不同类型的集合,它们更好/更pythonic?我可以使用哪些其他(更好)方法进行此项检查?

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'
Run Code Online (Sandbox Code Playgroud)

jte*_*ace 5

由于您已经在使用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
Run Code Online (Sandbox Code Playgroud)