Python ';int';对象不可下标(尝试展平列表)?
我正在尝试使用此代码来平展我的列表。我所说的“展平”是指将列表转换为Python ';int';对象不可下标(尝试展平列表)?,python,Python,我正在尝试使用此代码来平展我的列表。我所说的“展平”是指将列表转换为 [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):
[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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
展平(l)
文件“/Users/ashwin/.spyder-py3/untitled1.py”,第20行,扁平化
退货支票(aList)
文件“/Users/ashwin/.spyder-py3/untitled1.py”,第18行,检查
退货支票(L[i])
文件“/Users/ashwin/.spyder-py3/untitled1.py”,第16行,检查
返回检查(列表[i])
文件“/Users/ashwin/.spyder-py3/untitled1.py”,第13行,检查
如果类型(L[i])!=名单:
TypeError:“int”对象不可下标
我需要更改的是什么?您可以简化如下:
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
是什么。整数将引发您遇到的错误。这也消除了对全局变量的需求。这应该如何工作?为什么要将全局变量用于x
?为什么要使用全局变量来表示i
?为什么在一种情况下调用check(aList[i])
而在另一种情况下调用check(L[i])
呢?看起来check()
是递归的,但它不可能是递归的,因为没有只返回的基本情况。(加上全局函数和递归函数混合得不好)。关于这一点有很多问题,你以前做过搜索吗?我们这样解决问题,而不是代码审查。好例子!:)哦,我没注意到这是一个内部函数,德普
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]