Python:针对的存档迭代

问题描述

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

对不起,这听起来让您非常困惑。这是我正在尝试做的事情:

我有一个列表:


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

我正在寻找一个生成器来顺序产生# generator,yields [1,[5,6],[7,8]

对于上面的示例数组,让depth为2,深度在不同情况下会有所不同。

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


array = [
    [
        [1,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>

我认为问题是在嵌套循环中,在loop之后我无法调用yield

这整天让我感到困惑,如果有人提供帮助,我将感到非常高兴。


更新

感谢@Nick Parsons,指出了Can generators be recursive?,我可以继续研究,但遇到了递归超出错误:


array = [
    [
        [1,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,8]

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)