遍历嵌套列表,单个为

kra*_*032 1 python for-loop nested list python-3.x

我在列表中有一堆列表.嵌套深度在运行时确定,我只想访问它们到特定的(运行时决定的)深度,以任意方式操纵该级别的内容.

理想情况下,我希望能够像下面这样做:

for x in access_list(nested_list, d)
    # do stuff at nesting-depth d
Run Code Online (Sandbox Code Playgroud)

该怎么access_list做:

>>> mylist = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
>>> for d in range(4):
...     for l in access_list(mylist, d):
...         print((d, l))
(0, [[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
(1, [[[0, 1], [2, 3]])
(1, [[4, 5], [6, 7]]])
(2, [0, 1])
(2, [2, 3])
(2, [4, 5])
(2, [6, 7])
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(3, 5)
(3, 6)
(3, 7)
Run Code Online (Sandbox Code Playgroud)

我的尝试结果基本上没有做任何事情:

def access_list(lists, d):
    if not d:
        return lists
    return [access_list(_list, d-1) for _list in lists]
Run Code Online (Sandbox Code Playgroud)

它只是再次返回整个列表结构.我能做些什么来完成这项工作?

sch*_*ggl 6

这个生成器函数应该适用于嵌套列表并节省内存,因为它本身不构建列表,但是懒得生成项:

def access_list(nested_list):
    if not isinstance(nested_list, list):
    # if not isinstance(nested_list, (list, set)): you get the idea
        yield nested_list
    else:
        for item in nested_list:
            for x in access_list(item):
                yield x
            # in Python 3, you can replace that loop by:
            # yield from access_list(item)
    return

> l = [1, 2, [3, [4, 5], 6]]
> list(access_list(l))
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

如果要访问嵌套深度,以下将生成对(item, depth):

def access_list(nested_list, d=0):
    if not isinstance(nested_list, list):
        yield nested_list, d
    else:
        for item in nested_list:
            for x in access_list(item, d=d+1):
                yield x
    return

> l = [1, 2, [3, [4, 5], 6]]
> list(access_list(l))
[(1, 1), (2, 1), (3, 2), (4, 3), (5, 3), (6, 2)]
Run Code Online (Sandbox Code Playgroud)