遍历嵌套列表与单个 for



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

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

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)]

非常接近! 尝试将列表细分为逐渐变小的块。

def access_list(x, d):
    if d and isinstance(x, list) and x:
       return access_list(x[0], d-1) + access_list(x[1:], d-1)
    return [x]

好的,希望避免这种情况,因为它有点复杂,但这给出了您希望的确切输出:

def access_list(x, d):
    def _access_list(x, d):
        if d and isinstance(x, types.ListType) and x:
            return access_list(x[0], d-1) + access_list(x[1:], d)
        return [x]
    return filter(lambda x: x, _access_list(x, d))
你可以

使用 numpy 数组,它可能会起作用

import numpy
def access_list(lists, d):
    _lists=numpy.array(lists)
    if not d:
        L=[]
        for index in range(len(_lists)):
            L.append(_lists[index])
        return L
    return _lists[:]

请考虑以下解决方案:

def access_list(lists, d):
    if not d:
        return lists
    else:
        return sum(access_list(lists, d-1), [])

例如,使用此列表:l=[[[1,2],[3]],[[4],[5,[6,7]]]]

>>> access_list(l, 0)
[[1, 2], [3]]
[[4], [5, [6, 7]]]
>>> access_list(l, 1)
[1, 2]
[3]
[4]
[5, [6, 7]]
>>> access_list(l, 1)
1
2
3
4
5
[6, 7]

最新更新