【问题标题】:How to list values in a tree that satisfy certain predicates?如何列出满足某些谓词的树中的值?
【发布时间】:2016-03-10 18:33:04
【问题描述】:

这棵树是非二元的,因为它可以有两个以上的孩子。每个节点都有一个子节点列表。在这里,我正在编写list_if,它从树中返回满足谓词p 的值列表。当我测试我的代码时,它显示'int' object is not iterable。有人知道我怎么写代码吗?

def list_if(t, p):
    """
    Return a list of values in Tree t that satisfy predicate p(value).

    Assume p is defined on all of t's values.

    @param Tree t: tree to list values that satisfy predicate p
    @param (object)->bool p: predicate to check values with
    @rtype: list[object]

    >>> def p(v): return v > 4
    >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7, 8], 3)
    >>> list_ = list_if(t, p)
    >>> list_.sort()
    >>> list_
    [5, 6, 7, 8]
    >>> def p(v): return v % 2 == 0
    >>> list_ = list_if(t, p)
    >>> list_.sort()
    >>> list_
    [0, 2, 4, 6, 8]
    """  ###gather_lists() eliminates lists in list
    return gather_lists([t.value if p(t.value) else []] +[list_if(x, p) for x in t.children]) 

【问题讨论】:

  • 在哪里显示?

标签: python list python-3.x tree


【解决方案1】:

查看回溯(长错误消息)。就在上面写着这样的话:

TypeError: 'int' object is not iterable

应该显示发生错误的程序行。 (这就是为什么在您的问题中发布回溯会有所帮助。)

在这种情况下,程序试图迭代 int。口译员告诉你这是不可能的。

我怀疑有错误的行有for x in y:之类的东西,y是int而不是列表(如果错误在list_if函数中,请查看t.children。可能不是在构建树时正确设置)

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 2019-08-20
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多