从列表中制作列表中的平面列表(...由列表制成)

时间:2014-06-28 21:04:24

标签: python list

我一直在浏览SO python的常见问题并最终出现在这个问题中:Making a flat list out of list of lists in Python

所以我考虑的情况是你可以列出清单列表......

我想出了一个似乎有效的代码(我只尝试了代码中显示的情况),我想知道是否有更多的pythonic编写方式,因为我来自其他语言而且我&# 39;对于列表理解不是太多了。

1 个答案:

答案 0 :(得分:0)

test = [[[1,2,3],[4,5]], [6], [[7],8]]
test2 = [[1,2,3],[4,5]]
test3 = [1,2,3]

def createSuperList(l):
    sol = []
    for item in l:
        if (type(item) is list):
            for item2 in createSuperList(item):
                sol.append(item2)
        else:
            sol.append(item)
    return sol

print (createSuperList(test))
print (createSuperList(test2))
print (createSuperList(test3))