简体   繁体   English

如何使用 `return` 从 for 循环中取回多个值? 我可以把它们放在一个列表中吗?

[英]How can I use `return` to get back multiple values from a for loop? Can I put them in a list?

I have some code that prints data from a global dictionary named cal :我有一些代码可以从名为cal的全局字典中打印数据:

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

However, I want to use this code as part of a Discord bot.但是,我想将此代码用作 Discord 机器人的一部分。 In order for the bot to work properly, I need to return the data to another function that will actually send the message to the Discord chat.为了让机器人正常工作,我需要将数据return到另一个 function,它实际上会将消息发送到 Discord 聊天室。 Using print like above means that the message is displayed in my local console window, and the chat just sees None .使用上面的print意味着消息显示在我的本地控制台 window 中,并且聊天只看到None

I tried to fix it by using return instead:我试图通过使用return来修复它:

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

but this way, the for loop does not work properly.但是这样一来,for循环就不能正常工作了。 I only get at most one key-value pair from the dictionary.我最多只能从字典中得到一个键值对。

How can I fix this, so that all of the data is returned?我该如何解决这个问题,以便返回所有数据?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished.在循环内使用return会破坏它并退出 function,即使迭代仍未完成。

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 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:取而代之的是,您可以使用不同的方法:

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())

or you can iterate through it:或者你可以遍历它:

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: Append 你的数据到一个列表,然后在你的循环结束后返回它:

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

Or use a list comprehension:或使用列表推导:

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

Use a generator syntax (excellent explanation on SO here ):使用生成器语法(此处对 SO 进行了很好的解释):

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

for value, key in show_todo():
    print(value, key)

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 .任务存储在名为caldict 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 ).但是为了让机器人真正发送消息,我需要使用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语句使其打印到聊天中而不是控制台中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用循环和条件时如何从列表中获取唯一值 - How can I get unique values from a list when I use loop and condition 如何将来自 for 循环的各种元素放入列表中? - How can I put the various elements come from for loop in a list? 我该如何为这个给定列表添加循环? - how can i put for loop for this given list? 如何循环添加每个列表项并将它们放在一起? - How can I loop through adding each list item and put them together? 如何访问下面嵌套的 python 列表的各个值? 循环遍历我的列表以获取它们的最佳方法是什么? - How can I access the individual values my nested python list below? Whats the Best way to loop over my list to get them? 如何使用 for 循环构建可以从列表中读取值的字典? - How can I use for loop to build a dictionary that can reads values from a list? 我可以从内联获取多个返回值吗? - can I get multiple return values from inline for? 如何从字符串中获取年份并将其放入单独的列表中? - How can I get the years from a string and put it into a separate list? 如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中? - How can I remove unwanted characters from a words list and put them cleared in another list using Python? 如何子集数据框并将它们放在列表中? - How can I subset dataframe and put them on a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM