Is there a method I can utilise that: execute for
for n times?
Sorry, it may sounds extremely confusing to you. Here is what I am trying to do:
I have a list:
array = [
[
[1, 2],
[3, 4],
],
[
[100, 200],
[300, 400]
]
]
I seek for a generator to yields # generator, yields [1, 2], [3, 4], [5, 6], [7, 8]
sequentially.
for the example array above, let depth be 2, depth varies in different circumstance.
here is what I have tried so far:
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>
I think the issue is that in nested looping, I could not call loop
function after yield
It has confused me all day long, I will be so glad if someone offers some help.
Update
Thanks to @Nick Parsons, for pointing out Can generators be recursive?, I am able to work following out, but I got an recursion exceed error:
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