检查数组/元组/列表是否仅包含另一个数组/元组/列表中的元素的最佳方法是什么?
我尝试了以下两种方法,对于不同类型的集合,哪种方法更好/更符合 Python 风格? 我可以使用哪些其他(更好的)方法来进行此检查?
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'
最佳答案
由于您已经在使用 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
关于python - 检查集合是否仅包含另一个集合中的元素的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10521438/