Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

python - How to create a function for recursively generating iterating functions

I currently have a bit of Python code that looks like this:

for set_k in data:
    for tup_j in set_k:
        for tup_l in tup_j:

The problem is, I'd like the number of nested for statements to differ based on user input. If I wanted to create a function which generated n number of for statements like those above, how might I go about doing that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def nfor(data, n=1):
    if n == 1:
        yield from iter(data)
    else:
        for element in data:
            yield from nfor(element, n=n-1)

Demo:

>>> for i in nfor(['ab', 'c'], n=1):
...     print(i)
...     
ab
c
>>> for i in nfor(['ab', 'c'], n=2):
...     print(i)
...     
a
b
c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...