问题描述
因此,我正在开发一个聊天机器人,以解决不和谐的问题,现在正在开发一个可以用作待办事项列表的功能.我有一个命令可以将任务添加到列表中,并将它们存储在字典中.但是我的问题是以更易读的格式返回列表(请参见图片).
So I am working on a chat-bot for discord, and right now on a feature that would work as a todo-list. I have a command to add tasks to the list, where they are stored in a dict. However my problem is returning the list in a more readable format (see pictures).
def show_todo():
for key, value in cal.items():
print(value[0], key)
任务存储在名为cal
的dict
中.但是,为了使该机器人实际发送消息,我需要使用return
语句,否则它将仅将其打印到控制台而不是实际的聊天中(请参阅图片).
The tasks are stored in a dict
called cal
. But in order for the bot to actually send the message I need to use a return
statement, otherwise it'll just print it to the console and not to the actual chat (see pictures).
def show_todo():
for key, value in cal.items():
return(value[0], key)
这是我尝试解决的方法,但是由于我使用了return
,因此for循环无法正常工作.
Here is how I tried to fix it, but since I used return
the for-loop does not work properly.
那我该如何解决呢?如何使用return
语句,以便将其打印到聊天记录中而不是控制台中?
So how do I fix this? How can I use a return
statement so that it would print into the chat instead of the console?
推荐答案
即使循环尚未完成,在循环内使用return
也会破坏循环并退出函数.
Using a return
inside of a loop will break it and exit the function even if the iteration is still not finished.
例如:
def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1
在某些情况下,如果满足某些条件,我们需要中断循环.但是,在您当前的代码中,在完成循环之前先中断循环是无意的.
In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.
相反,您可以使用其他方法:
Instead of that, you can use a different approach:
def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key
您可以这样称呼它:
a = list(show_todo()) # or tuple(show_todo())
或者您可以遍历它:
for v, k in show_todo(): ...
将您的数据放入列表或其他容器中
将数据追加到列表中,然后在循环结束后返回:
Putting your data into a list or other container
Append your data to a list, then return it after the end of your loop:
def show_todo():
my_list = []
for key, value in cal.items():
my_list.append((value[0], key))
return my_list
或使用列表理解:
def show_todo():
return [(value[0], key) for key, value in cal.items()]
这篇关于如何在for循环中使用return语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!