Python - 如何在for循环中使用return语句?

Eri*_*c.L 6 python return function python-3.x

首先,我想为糟糕的头衔道歉,但这是我能做的最好的.我试图拍摄很多截图,希望能让它更容易理解.

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

def show_todo():
    for key, value in cal.items():
        print(value[0], key)
Run Code Online (Sandbox Code Playgroud)

任务存储在dict被调用的中cal.但是为了让机器人实际发送消息,我需要使用return语句,否则它只是将它打印到控制台而不是实际的聊天(见图片).

def show_todo():
    for key, value in cal.items():
        return(value[0], key)
Run Code Online (Sandbox Code Playgroud)

以下是我尝试修复它的方法,但由于我使用了返回,for循环无法正常工作.

那么我该如何解决这个问题呢?如何使用return语句将其打印到聊天而不是控制台?

请参阅图片以便更好地理解

Chi*_*xus 11

使用return循环内部,即使迭代仍未完成,也会将其分解并退出方法/函数.

例如:

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
Run Code Online (Sandbox Code Playgroud)

在某些情况下/算法中,如果满足某些条件,我们需要打破循环.但是,在当前的代码中,在完成循环之前打破循环是错误/糟糕的设计.

而不是那样,你可以使用不同的方法:

产生你的数据:

def show_todo():
    # Create a generator
    for key, value in cal.items():
        yield value[0], key
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

a = list(show_todo()) # or tuple(show_todo()) and you can iterate through it too.
Run Code Online (Sandbox Code Playgroud)

将数据附加到临时列表或元组或字典或字符串然后在循环退出后返回数据:

def show_todo():
    my_list = []
    for key, value in cal.items():
        my_list.append([value[0], key])
    return my_list
Run Code Online (Sandbox Code Playgroud)


Uri*_*iel 7

使用生成器语法(此处对 SO 的出色解释):

def show_todo():
    for key, value in cal.items():
        yield value[0], key

for value, key in show_todo():
    print(value, key)
Run Code Online (Sandbox Code Playgroud)