我有一个奇怪的问题,python将列表作为参数传递给函数.这是代码:
def foobar(depth, top, bottom, n=len(listTop)):
print dir(top)
print top.append("hi")
if depth > 0:
exit()
foobar(depth+1, top.append(listTop[i]), bottom.append(listBottom[i]))
top = bottom = []
foobar(0, top, bottom)
Run Code Online (Sandbox Code Playgroud)
它说"AttributeError:'NoneType'对象没有属性'append'",因为在foobar中top是None,尽管dir(top)打印了类型列表的完整属性和方法列表.那么什么是错的?我只是想将两个列表作为参数传递给这个递归函数.
Mar*_*ers 12
您传递的结果的top.append(),以你的函数.top.append()返回无:
>>> [].append(0) is None
True
Run Code Online (Sandbox Code Playgroud)
您需要.append()单独调用,然后传入top:
top.append(listTop[i])
bottom.append(listBottom[i])
foobar(depth+1, top, bottom)
Run Code Online (Sandbox Code Playgroud)
请注意,n=len(listTop)函数中的参数既冗余又只执行一次,即创建函数时.每次调用该函数时都不会对其进行评估.在任何情况下,您都可以从此处发布的版本中安全地省略它.