【问题标题】:Way to implement looking for NoneType within a for loop?在 for 循环中实现查找 NoneType 的方法?
【发布时间】:2021-08-10 07:51:41
【问题描述】:

在尝试将 NoneTypes 拉出此 for 循环时遇到问题,以免我的机器人因此错误而崩溃:

Ignoring exception in command rank:
Traceback (most recent call last):
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\Life\discordbot\main.py", line 232, in rank
    await ranking_menu.start(ctx)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\menus\__init__.py", line 967, in start
    await super().start(ctx, channel=channel, wait=wait)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\menus\__init__.py", line 707, in start
    self.message = msg = await self.send_initial_message(ctx, channel)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\menus\__init__.py", line 962, in send_initial_message
    kwargs = await self._get_kwargs_from_page(page)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\menus\__init__.py", line 939, in _get_kwargs_from_page
    value = await discord.utils.maybe_coroutine(self._source.format_page, self, page)
  File "E:\Programing\discordbot\lib\site-packages\discord\utils.py", line 343, in maybe_coroutine
    return await value
  File "D:\Life\discordbot\main.py", line 207, in format_page
    table = ("\n".join(f'{idx + 1}. {self.ctx.bot.get_user(entry[0]).name} (XP: {entry[1]} | Level: {entry[2]} \n'
  File "D:\Life\discordbot\main.py", line 207, in <genexpr>
    table = ("\n".join(f'{idx + 1}. {self.ctx.bot.get_user(entry[0]).name} (XP: {entry[1]} | Level: {entry[2]} \n'
AttributeError: 'NoneType' object has no attribute 'name'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "E:\Programing\discordbot\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'

它必须放在这一行,否则代码不能按预期工作,我很难做到这一点。感谢您提供任何和所有帮助!

        table = ("\n".join(f'{idx + 1}. {self.ctx.bot.get_user(entry[0]).name} (XP: {entry[1]} | Level: {entry[2]} \n'
                for idx, entry in enumerate(entries)))

再次感谢各位。

需要 iF,这是它所属的类!并且条目来自数据库中返回的行数

class LocalXpMenu(ListPageSource):
    def __init__(self, ctx, data):
        self.ctx = ctx
        super().__init__(data, per_page = 10)

    async def write_page(self, menu, fields=[]):
         offset = (menu.current_page * self.per_page) + 1
         len_data = len(self.entries)

         embed = Embed(title="Server XP Leaderboard",
                       colour=self.ctx.author.colour)
         embed.set_thumbnail(url = self.ctx.guild.icon_url)
         embed.set_footer(text = f"{offset:,} - {min(len_data, offset+self.per_page-1):,} of {len_data:,} members.")

         for name, value in fields:
             embed.add_field(name=name, value=value, inline=False)
         return embed

    async def format_page(self, menu, entries):
        fields = []

        table = ("\n".join(f'{idx + 1}. {self.ctx.bot.get_user(entry[0]).name} (XP: {entry[1]} | Level: {entry[2]} \n'
                for idx, entry in enumerate(entries)))

        fields.append(("Ranks", table))

        return await self.write_page(menu, fields)

【问题讨论】:

  • 如果get_user(entry) 为None,程序应该做什么?跳过?
  • 是的,很抱歉这么久才回复你,我今天很忙

标签: python sqlite discord.py


【解决方案1】:

使用for 循环添加条件 -

table = ("\n".join(f'{idx + 1}. {self.ctx.bot.get_user(entry[0]).name} (XP: {entry[1]} | Level: {entry[2]} \n' for idx, entry in enumerate(entries) if (entry and (len(entry) >= 3))))

【讨论】:

  • 我试过了,但我似乎仍然遇到同样的错误,所以我不太确定发生了什么
【解决方案2】:

您可以先过滤以仅选择非无条目。

mapped_entries = map(lambda entry: entry + [self.ctx.bot.get_user(entry[0])], entries)

filtered_entries = filter(lambda entry: entry[3] != None, mapped_entries)

table = ("\n".join(f'{idx + 1}. {entry[3].name} (XP: {entry[1]} | Level: {entry[2]} \n' for idx, entry in enumerate(filtered_entries)))

请注意,此示例中的 idx 将排除具有 None get_user 结果的条目。如果要包含这些,则必须在 mapped_entries 中包含索引并改用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2021-10-28
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2014-02-15
    相关资源
    最近更新 更多