首页 > 解决方案 > 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]:

它不起作用。

我怎样才能做到这一点?任何帮助将不胜感激

标签: pythonarrayspython-3.xpython-2.7object

解决方案


使用设置交集,如以下玩具示例中所示:

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

推荐阅读