我正在尝试使用此代码来压缩我的列表。通过展平我的意思是转换像
这样的列表[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
我需要改变什么?
答案 0 :(得分:4)
您可以简化如下:
def flatten(a_list):
x = []
def check(l):
# Note: check l, not l[i] because l can be anything in the recursive calls
if not isinstance(l, list):
x.append(l)
else:
for sub in l:
check(sub)
check(a_list)
return x
> flatten([1, 2, [3, 4, [[5], 6]]])
[1, 2, 3, 4, 5, 6]
l[i]
没有硬性访问权限,因为您永远不会l
。整数会引发您遇到的错误。这也消除了对全局变量的需求。