我正在创建一个不和聊天机器人。在Bot中,我想要制作一个打印出排名的命令。下面是代码:
rec= {'Boston': '3-0', 'Dallas': '2-1', 'Seattle': '0-3'}
def standings():
for team, win in rec.items():
return('{}: {}'.format(team, win))
@client.event
async def on_message(message):
if msg.startswith(".standings"):
s = standings()
await message.channel.send(s)
输出:
Boston: 3-0
预期输出:
Boston 3-0
Dallas 2-1
Seattle 0-3
如何使函数返回所有项,而不仅仅是一个?另外,如果我想ping与Teams具有相同名称的角色,我该如何做呢?我试着在"&;&;"前面加个@,但结果并不是这个角色。谢谢你的帮助。
试试这个:
def standings():
rows = ['{}: {}'.format(team, win) for team, win in rec.items()]
return 'n'.join(rows)
在for循环中使用return
在循环的第一次迭代中退出standings
函数。这就是为什么你只能在输出中看到第一个站着的人。
如果你想让函数返回一个包含所有排名的字符串,你可以这样做:
def standings():
return ', '.join(['{}: {}'.format(team, win) for team, win in rec.items()])
您可以使用如上所述的生成器。
rec = {'Boston': '3-0', 'Dallas': '2-1', 'Seattle': '0-3'}
def standings():
for team, win in rec.items():
yield '{}: {}'.format(team, win)
@client.event
async def on_message(message):
if message.startswith(".standings"):
for s in standings():
await message.channel.send(s)