提问者:小点点

Python无法检查值是否在列表中


所以我有这段代码,它选择列userID中的每一行,将返回的值放在字典中,然后打印它。

whitelist = []            

with db.cursor() as cursor:
    whitelist_get = "SELECT userID FROM whitelist;"
    cursor.execute(whitelist_get)
    whitelist = str(cursor.fetchall())
    print(whitelist)

这段代码检查来自discord的作者ID是否在该白名单中。

async def _function(ctx):
    global whitelist
    if ctx.message.author.id in whitelist:
        print("access granted")
    else:
        print("access not granted")

但是,当运行脚本时,代码会遍历全局白名单,然后它不会在if语句或else语句中进行处理。 它什么都不做。 它也不打印任何东西。 我做错什么了吗?

编辑:我的作者ID在MySQL表中,它应该打印授予访问权限,但它根本不打印任何内容。

Edit2:通过将白名单中的if ctx.message.author.id更改为白名单中的if str(ctx.message.author.id


共1个答案

匿名用户

FetchAll方法返回一个元组序列,因此您应该先解包元组以提取第一个项。 为了高效查找,您可以将白名单改为一个集合:

whitelist = {id for (id,) in cursor.fetchall()}