如何在 for 循环中使用 return 语句? [英] How to use a return statement in a for loop?

查看:110
本文介绍了如何在 for 循环中使用 return 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在开发一个用于不和谐的聊天机器人,现在正在开发一个可以作为待办事项列表的功能.我有一个命令将任务添加到列表中,它们存储在字典中.但是,我的问题是以更易读的格式返回列表(请参阅图片).

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)

任务存储在名为 caldict 中.但是为了让机器人真正发送消息,我需要使用 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 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆