【问题标题】:Python lists replace item with variable and fill remainderPython列表用变量替换项目并填充剩余部分
【发布时间】:2020-12-22 21:56:29
【问题描述】:

我正在为不和谐做一个单词猜测器,我偶然发现了一个我无法弄清楚的问题。完整代码here.

我有一个关键字、一个计数器和一个单词帮助列表。我每隔 x 秒调用一个函数,它将根据计数器从关键字向 wordhelp 列表添加一个字母。

我的问题是:如何将 wordhelp 列表作为len(keyword) 的点开始,然后将每个点替换为函数中对应的字母。

我尝试过这样的事情:wordhelp[counter] = keyword[counter],但这给了我list assignment index out of range,因为 wordhelp 列表中没有点可以被替换。

    def __init__(self, bot):
        self.bot.counter = 0
        self.bot.keyword = ""
        self.bot.wordhelp = []

    # Called every 60 seconds
    @tasks.loop(seconds=60)
    async def loop_update(self):
        # Add the new letter to the wordhelp list
        self.bot.wordhelp[self.bot.counter] = self.bot.keyword[self.bot.counter]
        # Edit the ini variable embed to show new keyword letter
        await self.bot.ini.edit(embed=discord.Embed(title="Guessing game started!", description=f"Find the keyword starting with:\n`{''.join(self.bot.wordhelp)}`"))
        self.bot.counter += 1

【问题讨论】:

  • 在问题中发布您的代码,而不是作为链接。最好采用minimal reproducible example 的形式。
  • 当然!虽然有点难,因为它在课堂上
  • bot是什么类?
  • bot 是我的 commands.Bot 实例,我将变量分配给它,以便它们可以在不同的功能上进行编辑
  • 基本上我只需要知道如何使self.bot.wordhelp列表点的长度为self.bot.wordhelp

标签: python-3.x list discord.py-rewrite


【解决方案1】:

您可以只计算要“显示”的字母数量,而不是保留一个明确的点列表,然后根据它动态创建显示。像这样的:

def hidden_word(word, reveal=0):
    hidden = len(word) - reveal
    dots = '.' * hidden
    return word[:reveal] + dots

现在您可以向它输入要显示的字母数:

word = 'giraffe'
for i in range(len(word)+1):
    print(hidden_word(word, reveal=i))
# Produces:
.......
g......
gi.....
gir....
gira...
giraf..
giraff.
giraffe

【讨论】:

  • 非常感谢!虽然我遇到了一个问题,例如,如果我希望关键字是多个单词,那么空格会显示为点。我不确定如何实现一个功能,其中空格显示为空格,其余显示为点。
  • @Buster 您可以将单词拆分,根据计数器分别隐藏每个单词,然后使用 ' '.join() 重新加入。
猜你喜欢
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2022-01-08
  • 1970-01-01
相关资源
最近更新 更多