我写了这个函数:
def append_to_all(L, v):
'''Append value v, which may be of any type, to all the nested lists in L.
L is a list, and may contain other lists.'''
if len(L) == 0:
return L.append(v)
elif isinstance(L[0], list):
L[0].append(v)
return append_to_all(L[1:], v)
else:
return append_to_all(L[1:], v)
if __name__ == '__main__':
L = [1, 2, [3]]
append_to_all(L, 'a')
print L # should return [1, 2, [3, 'a'], 'a']
函数返回[1,2,[3,'a']],而不是[1,2,[3,'a'],'a']。我试过调试,但它找不出错误。似乎当len(L)==0函数被调用时,“a”被追加到空列表中,而不是全局L中
我该怎么解决这个问题?你知道吗
谢谢你!你知道吗
L[1:]
生成列表的副本。这是一份全新的清单,除了第一项外,所有的东西都有副本。如果向其中添加元素,则对原始列表没有影响。因此,当您附加到空列表时,它只附加到空列表,而不是它前面的任何列表。你知道吗为了递归地执行此操作,您不应该附加到列表,而应该返回新列表
但这并不是使用递归的地方。迭代解法更简单、更有效。你知道吗
相关问题 更多 >
编程相关推荐