python - Python 如果数组中的任何项目都存在于对象中
问题描述
我想检查给定对象中是否存在数组中的任何项目。
这是我当前有效的代码:
if "Mod" in [role.name for role in data.roles]:
但如果我这样做....
roles = ["Mod", "Admin"]
if any(roles) in [role.name for role in data.roles]:
它不起作用。
我怎样才能做到这一点?任何帮助将不胜感激
解决方案
使用设置交集,如以下玩具示例中所示:
roles = ["Mod", "Admin"]
if set(roles).intersection(["Mod"]):
print("match")
输出
match
在您的示例中,它将是这样的:
if set(roles).intersection([role.name for role in data.roles]):
do something
或者,如果您愿意:
roles = ["Mod", "Admin"]
data_roles = set(role.name for role in data.roles)
if any(role in data_roles for role in roles):
do something
推荐阅读
- javascript - 有没有办法使用 google-map-react 从这个可拖动的标记中获取坐标?
- react-native - react native 中的共享库和 .h 导入
- python - Python:如何将列表迭代到另一个列表?
- c++ - 在子窗口中使用 winapi 在 C++ 中创建按钮不起作用
- r - 试图从 ggplot 中重现 ANOVA 测试箱线图
- amazon-web-services - AWS Cognito 用户池禁用登录按钮
- python - 网格中的 Tkinter 标签异常扩展
- python - 为什么我的 tksheet tkinter 窗口滚动条在调整大小后被隐藏?
- javascript - React Native:何时使用箭头函数
- pie-chart - 空对象引用上的 MPAndroidChart PieChart setData