Skip to main content
 首页 » 编程设计

python之用单个 for 遍历嵌套列表

2025年05月04日12Renyi-Fan

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

理想情况下,我希望能够像这样简单地做到这一点:

for x in access_list(nested_list, d) 
    # do stuff at nesting-depth d 

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) 

我的尝试实际上什么也没做:

def access_list(lists, d): 
    if not d: 
        return lists 
    return [access_list(_list, d-1) for _list in lists] 

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

请您参考如下方法:

此生成器函数应该适用于嵌套列表并节省内存,因为它本身不构建列表,而是延迟生成项目:

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] 

如果你想访问嵌套深度,下面将生成对 (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)]