Python - 如何在 for 循环中使用 return 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44564414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - How to use a return statement in a for loop?
提问by Eric.L
First of all I want to apologize for the bad title, but it was the best I could do. I tried to take a lot of screenshots to hopefully make this a little bit easier to understand.
首先,我想为糟糕的标题道歉,但这是我能做的最好的事情。我试着截取了很多截图,希望能让这更容易理解。
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)
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).
任务存储在一个dict
名为cal
. 但是为了让机器人真正发送消息,我需要使用 return 语句,否则它只会将其打印到控制台而不是实际聊天(见图)。
def show_todo():
for key, value in cal.items():
return(value[0], key)
Here is how I tried to fix it, but since I used return the for-loop does not work properly.
这是我尝试修复它的方法,但由于我使用了 return,for 循环无法正常工作。
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 语句使其打印到聊天中而不是控制台中?
Please see the pictuesfor a better understanding
请看图片以便更好地理解
回答by Chiheb Nexus
Using a return
inside of a loop, will break it and exit the method/function even if the iteration still not finished.
使用return
循环内部,即使迭代仍未完成,也会中断它并退出方法/函数。
For example:
例如:
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/algorithms we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it it is an error/bad design.
在某些情况/算法中,如果满足某些条件,我们需要中断循环。但是,在您当前的代码中,在完成循环之前打破循环是错误/糟糕的设计。
Instead of that, you can use a different approach:
取而代之的是,您可以使用不同的方法:
yielding your data:
产生你的数据:
def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key
You can call it like:
你可以这样称呼它:
a = list(show_todo()) # or tuple(show_todo()) and you can iterate through it too.
Appending your data into a temporar list or tuple or dict or stringthen after the exit of your loop return your data:
将您的数据附加到临时列表或元组或字典或字符串中,然后在循环退出后返回您的数据:
def show_todo():
my_list = []
for key, value in cal.items():
my_list.append([value[0], key])
return my_list