2017-10-05 48 views
-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 

这是什么我需要改变?

+0

这应该如何工作?你为什么使用全局的'x'?你为什么使用全局的'i'?你为什么在一个情况下调用'check(aList [i])'而在另一个情况下调用(L [i])''? – khelwood

+0

它看起来像'check()'是递归的,但它不能是因为没有基本的情况下,你只是返回。 (加全局和递归不能很好地混合)。 – quamrana

+0

关于这个问题有多个问题,你之前做过搜索吗?我们解决SO问题,而不是代码评论。很好的例子! :) –

回答

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是什么。整数会引发您遇到的错误。这也摆脱了对全局变量的需求。

+0

哦,我没有注意到它是一个内部函数,derp – Felk