Python:存档迭代

Python: archive iteration on for

有没有我可以利用的方法:执行 for n 次?

抱歉,这听起来可能让您非常困惑。这是我正在尝试做的事情:

我有一个列表:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

我寻找一个生成器来按顺序产生 # generator, yields [1, 2], [3, 4], [5, 6], [7, 8]

对于上面的示例数组,让深度为2,深度因情况而异。

这是我到目前为止尝试过的方法:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

# set a con, increment by 1 before each `for`
con = 0
depth = 2


def loop(arr):
    global con
    con += 1
    if con == depth:
        for i in arr:
            # the only place to exit the function
            yield i
    else:
        for i in array:
            # nest looping
            yield loop(i)


for ll in loop(array):
    print(ll)


# expected output
# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]

# however I got
# <generator object loop at 0x7f8cc815ac80>
# <generator object loop at 0x7f8cc818c2e0>

我认为问题是在嵌套循环中,我无法在 yield

之后调用 loop 函数

困扰了我一整天,如果有人能提供帮助,我会很高兴。


更新

感谢@Nick Parsons 指出 ,我可以继续工作,但出现递归超出错误:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

# set a con, increment by 1 before each `for`
con = 0
depth = 2


def loop(arr):
    global con
    con += 1
    if con == depth:
        for i in arr:
            # the only place to exit the function
            yield i
    else:
        for i in array:
            # nest looping
            yield from loop(i)


for ll in loop(array):
    print(ll)


# expected output
# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]

# however I got
RecursionError: maximum recursion depth exceeded in comparison

正如 中指出的那样,您的问题是您正在使用

yield loop(i)

哪个 returns 发电机,你应该在哪里使用

yield from loop(i)

从递归中产生值。

请注意,您可以通过检查传递给函数的列表元素的类型并在它们是列表时进行递归来简化代码并使其灵活地处理任何深度的嵌套列表:

def loop(arr):
    if type(arr[0]) is list:
        for a in arr:
            yield from loop(a)
    else:
        yield arr

for ll in loop(array):
    print(ll)

输出:

[1, 2]
[3, 4]
[100, 200]
[300, 400]