python - 检查集合是否仅包含另一个集合中的元素的最佳方法?

标签 python

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

我尝试了以下两种方法,对于不同类型的集合,哪种方法更好/更符合 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/

相关文章:

python - django 开发服务器,将 header 添加到静态文件

python - 如何销毁放置在 if 条件中的按钮小部件? Tkinter

python - 如何在遗传算法工具箱Deap中生成0到1之间的随机数

python - Django 空表单字段验证不适用于干净的方法

python - 从我的 Django 应用程序拒绝连接到 Minio Docker 实例

python - 用于 Python 开发的 Sublime 与 PyCharm

python - 在 Python 中将数据发布到 api 时无法将 str 连接到字节错误

python - 摆脱Python pandas中的SettingWithCopyWarning

python - 使自定义类表现得像集合

Python zipfile 模块创建多个同名文件