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]
作为一个开始,我建议你分手很复杂将理解列入逐行逻辑流程并查看其行为是否相同。当你以这种方式重构你的代码时,你可以添加'print'行来调试你的代码,并确保每一步都在做你想做的事情。您可以在最后将其重新组合回理解中。 –
从文档字符串中不清楚该函数是否应该将嵌套列表弄平。在我的回答中,我认为它是这样,但这可能不正确(这不包括在任何文件中)。 – Blckknght