Python 列出用变量替换项目并填充余数
Python lists replace item with variable and fill remainder
我正在为 discord 猜词,我偶然发现了一个我无法解决的问题。完整代码 here.
我有一个关键字、一个计数器和一个 wordhelp 列表。我每 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
无需保留明确的点列表,您可以只计算要 'reveal' 的字母数量,然后基于此动态创建显示。像这样:
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
我正在为 discord 猜词,我偶然发现了一个我无法解决的问题。完整代码 here.
我有一个关键字、一个计数器和一个 wordhelp 列表。我每 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
无需保留明确的点列表,您可以只计算要 'reveal' 的字母数量,然后基于此动态创建显示。像这样:
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