简体   繁体   English

如何返回值并且不中断循环

[英]How to return value and don't break loop

I want to create tool, which will parse and return messages from my email.我想创建一个工具,它将解析并从我的电子邮件中返回消息。 You can see part of my code below.你可以在下面看到我的部分代码。 This is very simpliest part, in reality code much bigger.这是非常简单的部分,实际上代码要大得多。 I have at least 2 iterations on 'for' loop and I want to return each result of operation, but return breaks the loop.我在 'for' 循环上至少有 2 次迭代,我想返回每个操作结果,但返回会中断循环。 I can add results to list, but I need just string, not list.我可以将结果添加到列表中,但我只需要字符串,而不是列表。 The best way for me it's return result and continue loop, but this is impossible.对我来说最好的方法是返回结果并继续循环,但这是不可能的。 Maybe I need to define new function or use lambda function for it and get result recursively?也许我需要定义新函数或为其使用 lambda 函数并递归获取结果? I didn't works with recursion before.我以前没有使用递归。 Also I know that this is possible to use 'yield', but how to returns values from generator then?我也知道这可以使用 'yield',但是如何从生成器返回值呢?

def a(request_url):
output = getImap(request_url)

def getImap(request_url):
    #many code before.....
    mail = imaplib.IMAP4_SSL(output['hostname'], port=output['port'])
    typ, data = mail.fetch(output['parameter']['uid'], 'RFC822')
    msg = email.message_from_string(data[0][1])
    for part in msg.walk():
        res = part.get_payload(decode=True)
        return res

def AcceptDef(res):
    print res

Hopefully I understood enough of the question and this can help you.希望我对这个问题有足够的理解,这可以帮助你。 There are two ways to go about what you're trying to do, depending on what your end design is.根据您的最终设计,有两种方法可以完成您的工作。

Either you call the function you want for each item (within your loop):要么为每个项目调用所需的函数(在循环中):

for part in msg.walk():
    res = part.get_payload(decode=True)
    AcceptDef(res)

Or you can yield instead of return creating a generator over which you can iterate.或者您可以使用yield而不是 return 创建一个可以迭代的生成器。

def walker(amount):  # stands in for getting wanted items.
    for item in range(amount):
        yield item

def printer(text):   # stands in for your action
    print(text)

for i in walker(5):  # iterate over all items ...
    printer(i)       # ... calling a corresponding action

EDIT: as tobias_k pointed out in the comment.编辑:正如 tobias_k 在评论中指出的那样。 If you need to perform different action on different iterations, but still prefer to do so from within the loop, you could of course pass this in as an argument and perform accordingly.如果您需要对不同的迭代执行不同的操作,但仍然更喜欢在循环内执行此操作,您当然可以将其作为参数传递并相应地执行。 An example:一个例子:

def rinseandrepeat(amount, fce):
    for item in range(amount):
        fce(item)

def printer1(text):
    print('P1:', text)

def printer2(text):
    print('P2:', text)

rinseandrepeat(2, printer1)  # calls printer1() for each item
rinseandrepeat(2, printer2)  # calls printer2() for each item

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM