-1
我正在尝试使用此代码来压扁我的列表。通过扁平化我的意思是将像'int'对象不是可下载的(试图压扁列表)?
[1,[2], [[[[3]]]],4]
列表为
[1,2,3,4]
这里是我的代码
i = 0
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
global x
x = []
def check(L):
global i
if type(L[i]) != list:
x.append(L[i])
i += 1
return check(aList[i])
else:
return check(L[i])
return check(aList)`
,我不断收到此错误
Traceback (most recent call last):
File "<ipython-input-87-ee05c7b1d059>", line 1, in <module>
flatten(l)
File "/Users/ashwin/.spyder-py3/untitled1.py", line 20, in flatten
return check(aList)
File "/Users/ashwin/.spyder-py3/untitled1.py", line 18, in check
return check(L[i])
File "/Users/ashwin/.spyder-py3/untitled1.py", line 16, in check
return check(aList[i])
File "/Users/ashwin/.spyder-py3/untitled1.py", line 13, in check
if type(L[i]) != list:
TypeError: 'int' object is not subscriptable
这是什么我需要改变?
这应该如何工作?你为什么使用全局的'x'?你为什么使用全局的'i'?你为什么在一个情况下调用'check(aList [i])'而在另一个情况下调用(L [i])''? – khelwood
它看起来像'check()'是递归的,但它不能是因为没有基本的情况下,你只是返回。 (加全局和递归不能很好地混合)。 – quamrana
关于这个问题有多个问题,你之前做过搜索吗?我们解决SO问题,而不是代码评论。很好的例子! :) –