0

可能重复:
在 Python 中展平(不规则)列表列表

有没有一种方法可以存储结果而不必编写每个子列表名称?每个数组中的数字只是我想要做的例子。先感谢您。

        _store = []

        _arr4 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        _arr3 = [1, 2, 3, _arr4, 5, 6, 7, 8, 9]
        _arr2 = [1, 2, 3, 4, 5, 6, _arr3, 8, 9]
        _arr = [1, 2, 3, _arr2, 5, 6, 7, 8, 9]

        for _value in _arr:

            #If value is a list get it, go over that list and so on
            if isinstance( _value, list ):

                _store.append(_value)
                _sub_list = _value

                if isinstance( _sub_list, list ):

                    _store.append( _sub_list)
                    _sub_sub_list = _sub_list

                    if isinstance( _sub_sub_list, list ):

                        _store.append( _sub_list)
                        _sub_sub_sub_list = _sub_list

                        #and so on...

        print _store
4

3 回答 3

3

使用递归:

a = [1,2,3]
b = [4,a,5]
c = [6,b,7]

def add_to(input, output):
    for x in input:
        if isinstance(x, list):
            add_to(x, output)
        else:
            output.append(x)

result = []

add_to(c, result) # now result = [6, 4, 1, 2, 3, 5, 7]

可以通过使用生成器来消除通过递归传递输出 ref 的非 Python 性:

def flatten(input):
    for x in input:
        if isinstance(x, list):
            for y in flatten(x):
                yield y
        else:
            yield x

result = list(flatten(c))
于 2012-11-22T18:37:13.050 回答
1

您可以尝试使用递归:

arr4 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr3 = [1, 2, 3, arr4, 5, 6, 7, 8, 9]
arr2 = [1, 2, 3, 4, 5, 6, arr3, 8, 9]
arr = [1, 2, 3, arr2, 5, 6, 7, 8, 9]

def get_store(array):
    store = []
    for item in array:
        if isinstance(item, list):
            store.extend(get_store(item))
        else:
            store.append(item)
    return store

print get_store(arr)

...输出:

[1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 8, 9, 5, 6, 7, 8, 9]

基本上,每当您注意到您正在执行某些操作并不断地嵌套或重复它,但难以将其转换为 for 循环时,这是您可以尝试递归的好兆头。

于 2012-11-22T18:42:15.240 回答
1

为什么不直接将列表序列化为 JSON?

import json
json.dumps(arr)
于 2012-11-22T18:38:20.783 回答