【问题标题】:Python failing to check if a value is in a listPython无法检查值是否在列表中
【发布时间】:2020-10-09 18:37:50
【问题描述】:

所以我有这段代码选择列 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")

但是,在运行脚本时,代码会超过 global whitelist,然后它不会在 if 语句或 else 语句中执行。它什么也不做。它也不打印任何东西。我做错什么了吗?

编辑:我的作者 ID 在 MySQL 表中,它应该打印 access granted 但它根本不打印任何内容。

EDIT2:通过将if ctx.message.author.id in whitelist: 更改为if str(ctx.message.author.id) in whitelist: 解决

【问题讨论】:

  • 你能分享一个截图显示你是如何调用这个函数的吗?
  • @GPhilo 嗨,这是一个不和谐的机器人命令,所以它在async def 之前只有@bot.command(name="function"),并且每当我键入命令“simi function”时都会调用该函数。

标签: python mysql discord.py-rewrite


【解决方案1】:

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

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

【讨论】:

  • 这确实是一个进步,它现在打印“未授予访问权限”,但是我的作者 ID 在“用户 ID”列中,它应该打印“授予访问权限”
  • @IonutSauciuc 您的第一个脚本将whitelist 转换为字符串,您可能希望将结果改为whitelist.append(或至少连接到现有项目)
  • ctx.message.author.id和列userID是什么数据类型?
  • @GPhilo 我尝试追加,但它仍然没有打印任何内容。 @blhsing ctx.message.author.id 是 int,userID 列是 VARCHAR。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 2013-08-07
  • 2017-12-21
  • 1970-01-01
  • 2019-10-23
  • 2018-05-10
相关资源
最近更新 更多