我正在创建一个不和谐的机器人,我做了一个!爱的命令,它是测试两个人或实体之间的爱率。
例句:!爱玛
结果:佩米斯蒂尔和艾玛之间的关系是x%。
下面是代码:
@bot.command(name="love", aliases=["l"])
async def love(ctx, Personne1, Personne2):
if ctx.message.channel.id != 763352957579690018:
printIt = 1
wordBanList = ['@everyone', '@here', '<@&763489250162507809>','<@&777564025432965121>','<@&822200827347075132>',
'<@&763815680306184242>','<@&764422266560839680<','<@&763815728972300338>','<@&763815728972300338>',
'<@&763815228323528725>','<@&763815784904261632>','<@&764422166116171806>','<@&764422057353936897>',
'<@&804807279043674143>','<@&828664814678179861>','<@&823562218095640646>','<@&823638574809219163>']
LoveRate = str(random.randrange(0, 100))
for y in range(len(wordBanList)):
if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
printIt = 0
if(printIt == 0):
await ctx.send("Tu t'es pris pour qui ?")
if debug == True:
print("[DEBUG] !love : Someone tried to use a banned word !")
else:
await ctx.send("L'amour entre **"+Personne1+"** et **"+Personne2+"** est de **"+LoveRate+"%** <:flushed:830502924479758356>")
if debug == True:
print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))
else:
botChannel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
messageBot = await ctx.send("Va faire cette commande dans "+botChannel.mention+" ou je te soulève <:rage:831149184895811614>")
await asyncio.sleep(5)
await ctx.message.delete()
await messageBot.delete()我很确定这段代码是可优化的,但我不知道怎么做,有人能帮我吗?)
发布于 2021-04-12 19:42:15
中的索引。
在Python中,通常不推荐这种模式:
for y in range(len(wordBanList)):
if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
printIt = 0您几乎不需要通过它们的索引来迭代和访问元素。相反,您应该直接迭代可迭代的元素:
for word in wordBanList:
if Personne1 == word or Personne2 == word:
printIt = 0还请注意,您不需要or语句周围的括号。
如果您也需要索引,可以使用内置的enumerate:
for index, word in enumerate(wordBanList):
...正如Harsha所指出的,sets是针对成员资格测试而优化的,所以在可能的情况下使用它们。这样做还可以使printIt的分配更加简洁:
wordBanList = {'@everyone', '@here', '<@&763489250162507809>', ...}
printIt = 0 if (Personne1 in wordBanList or Personne2 in wordBanList) else 1这里也不需要副词,但可能会提高可读性。
函数名应该是小写,必要时用下划线分隔单词,以提高可读性。变量名与函数名遵循相同的约定。
变量和函数名应该跟随snake_case。
debug == True作为一般的经验法则,您应该始终将is与内置常量:True、False和None一起使用。检查debug的真实性(if debug:)也足够了。但是,这取决于用例,因为表达式不是等价的。对于所有falsey值,第二个都会失败,而不仅仅是False (例如空字符串、空列表)。如果您感兴趣,可以阅读更多关于Truthy和Falsy在Python中的价值的内容。
LoveRate = str(random.randrange(0, 100))LoveRate (或更好的love_rate)不应该是str类型,因为您只需要它的str-represantation来打印它。通过使用F-字符串,您可以让Python处理格式设置。那样的话,你就不必再考虑向str转换了。
print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))变成了
print(f"[DEBUG] !love : The love rate ({LoveRate}%) between {Personne1} and {Personne2} has been printed in channel ID {ctx.channel.id}")还有几个小问题:
if-else-block中不同,我们可以使用ctx.message.channel.id == 763352957579690018作为退出条件。print_it的类型是int,但基本上是bool类型的变量。我们也可以完全消除这个变量,因为我们只使用它一次。@bot.command(name="love", aliases=["l"])
async def love(ctx, personne1, personne2):
if ctx.message.channel.id == 763352957579690018:
bot_channel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
message_bot = await ctx.send(f"Va faire cette commande dans {bot_channel.mention} "
f"ou je te soulève <:rage:831149184895811614>")
await asyncio.sleep(5)
await ctx.message.delete()
await message_bot.delete()
return
word_ban_list = {'@everyone', '@here', '<@&763489250162507809>', '<@&777564025432965121>',
'<@&822200827347075132>', '<@&763815680306184242>', '<@&764422266560839680<',
'<@&763815728972300338>', '<@&763815728972300338>', '<@&763815228323528725>',
'<@&763815784904261632>', '<@&764422166116171806>', '<@&764422057353936897>',
'<@&804807279043674143>', '<@&828664814678179861>', '<@&823562218095640646>',
'<@&823638574809219163>'}
love_rate = str(random.randrange(0, 100))
if personne1 in word_ban_list or personne2 in word_ban_list:
await ctx.send("Tu t'es pris pour qui ?")
if debug:
print("[DEBUG] !love : Someone tried to use a banned word !")
else:
await ctx.send(f"L'amour entre **{personne1}** et **{personne2}** est de **{love_rate}%** "
f"<:flushed:830502924479758356>")
if debug:
print(f"[DEBUG] !love : The love rate ({love_rate}%) between {personne1} and"
f"{personne2} has been printed in channel ID {ctx.channel.id}")发布于 2021-04-12 18:13:27
for y in range(len(wordBanList)):
if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
printIt = 0这段代码正在检查Personne1或Personne2是否在wordBanList中,是否有O(len(wordBanList))运行时时间。您可以将wordBanList的数据类型更改为set(),并具有O(1)运行时。因此,您的代码可以转换为:
if Personne1 in wordBanList or Personne2 in wordBanList:
printIt = 0P.S:如果你有一个小的wordBanList (比如<100个单词),把wordBanList作为一个列表与集合没有太大的不同。但是,当有大量的单词(>10,000,000)时,差异是显著的。https://towardsdatascience.com/faster-lookups-in-python-1d7503e9cd38
https://codereview.stackexchange.com/questions/259422
复制相似问题