【发布时间】:2021-01-10 07:17:58
【问题描述】:
有没有我可以利用的方法:执行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 指出Can generators be recursive?,我能够继续工作,但出现递归超出错误:
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
【问题讨论】:
-
这能回答你的问题吗? Can generators be recursive?
标签: python loops for-loop iteration yield