如何递归地实现有关嵌套列表的以下方法?

时间:2016-03-03 02:33:28

标签: python list python-3.x recursion nested

这里我们试图生成一个包含obj元素的新列表,如果元素的长度大于n。我的代码没有通过doctest,因为它在list_over上失败了(“five”,3);它打印“[]”时应该打印“[5]”。然而,doctest传递了其他docstring示例。但我很难纠正它。有人可以帮忙吗?

def list_over(obj, n):
    """
    Return a list of strings of length greater than n in obj, or sublists of obj, if obj
    is a list.  Otherwise, if obj is a string return a list containing obj if obj has
    length greater than n, otherwise an empty list.

    @param str|list obj: possibly nested list of strings, or string
    @param int n: non-negative integer
    @rtype: list[str]

    >>> list_over("five", 3)
    ['five']
    >>> list_over("five", 4)
    []
    >>> L = list_over(["one", "two", "three", "four"], 3)
    >>> all([x in L for x in ["three", "four"]])
    True
    >>> all([x in ["three", "four"] for x in L])
    True
    """

    return [list_over(x, n) if isinstance(x,list) else x for x in obj  if len(x)>n]

1 个答案:

答案 0 :(得分:2)

我认为你不应该试图将该函数的某些复杂逻辑楔入列表理解中。有些情况下你会出错(比如更深层次的嵌套列表和成员少于n的列表)。

相反,我建议编写一个函数来处理obj是一个字符串的基本情况,以及它不是的递归情况:

def list_over(obj, n):
    if isinstance(obj, str): # base case
        if len(obj) > n:
            return [obj]
        else:
            return []

    result = []
    for item in obj:
        result.extend(list_over(item, n)) # recursive case
    return result