简体   繁体   English

python-从递归函数返回平面对象列表

[英]python - return flat list of objects from recursive function

I have a recursive function which loops through any number of objects, and their children collecting children who's age meets the filtered ages. 我有一个递归函数,它遍历任何对象,并且他们的孩子收集年龄符合过滤年龄的孩子。

In this case I'm looking to loop through each Person and their children collecting any Person who's age is either 2 or 4. However I'm not entirely sure how to continuously build a single list and then return it. 在这种情况下,我希望遍历每个人及其孩子,以收集年龄为2或4岁的任何人。但是,我不确定如何连续构建单个列表然后将其返回。 Right now it just returns the last found Person. 现在,它只返回最后找到的Person。

UPDATED I've made a few changes to the recursive function to always append to the passed variable. 更新我对递归函数进行了一些更改,以始终附加到传递的变量中。 Is this a proper solution? 这是一个合适的解决方案吗?

from random import randint

NODES = []

class Person():
    def __init__(self, name="", age=0, children=None):
        self.name = name
        self.age = (randint(0,4))
        self.children = children if children is not None else []

for x in xrange(5):
    new = Person()
    NODES.append( new )
    for c in xrange(5):
        new.children.append( Person() )


def get_nodes(items=[], ages=[], results=[]):
    print "Searching..."
    # pseudo code
    for item in items:
        if item.age in ages:
            print "\t","valid age"
            results.append(item)

        results + get_nodes(items=item.children, ages=ages, results=results)

    return results


AGED_NODES = get_nodes( items=NODES, ages=[2, 4], results=[])
print len(AGED_NODES)
print AGED_NODES

It has always seemed more logical for me that a recursive function like get_nodes should only return its own results - the caller can add on its own results, and the caller's caller does the same. 在我看来,像get_nodes这样的递归函数仅应返回其自身的结果似乎更加合乎逻辑-调用者可以添加自己的结果,而调用者的调用者也可以这样做。 So no I wouldn't pass 'results' into get_nodes. 因此,不,我不会将“结果”传递给get_nodes。

Also note that your line: 另请注意,您的行:

results + get_nodes(items=item.children, ages=ages, results=results)

does nothing. 什么也没做。

So my version of your code would look like: 所以我的代码版本如下所示:

def get_nodes(items=[], ages=[]):
    myresults = []
    print "Searching..."
    # pseudo code
    for item in items:
        if item.age in ages:
            print "\t","valid age"
            myresults.append(item)

        myresults.extend( get_nodes(items=item.children, ages=ages) )

    return myresults

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

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