2016-03-03 40 views
0

这里我们试图生成一个包含来自obj的元素的新列表,如果这些元素的长度大于n。我的代码没有通过doctest,因为它在list_over上失败(“five”,3);当它打印“[五]”时,其打印“[]”。但doctest通过其他文档字符串示例。但我很难纠正它。有人可以帮忙吗?如何递归实现关于嵌套列表的以下方法?

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

作为一个开始,我建议你分手很复杂将理解列入逐行逻辑流程并查看其行为是否相同。当你以这种方式重构你的代码时,你可以添加'print'行来调试你的代码,并确保每一步都在做你想做的事情。您可以在最后将其重新组合回理解中。 –

+0

从文档字符串中不清楚该函数是否应该将嵌套列表弄平。在我的回答中,我认为它是这样,但这可能不正确(这不包括在任何文件中)。 – Blckknght

回答

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