我必须解决的问题是将嵌套列表作为输入,并返回相同的嵌套列表,但每个元素都是先前存在于该位置的元素的平方。这是我的代码
>>> def treemap(lst):
... for element in lst:
... if element == type(list):
... return treemap(element)
... else:
... element=element**2
... return lst
>>> lst = [1, 2, 3, [4, [5, 6], 7]]
>>> print(treemap(lst))
现在我收到一个错误,指出“int”对象不可迭代。我假设这意味着它正在尝试运行整数类型的循环,这对我来说没有意义,因为我只为列表类型重新运行该函数。
Do not return
在递归调用中,一旦返回,您将停止处理所有剩余元素
element == type(list)
是不正确的,因为type(list)
is <class 'type'>
它永远不会等于列表中的任何项目。使用isinstance
instead
在基本情况下,您需要通过索引访问元素才能反映更改
def treemap(lst):
for i, element in enumerate(lst):
if isinstance(element, list):
treemap(element)
else:
lst[i] = lst[i]**2
return lst
Output:
[1, 4, 9, [16, [25, 36], 49]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)