How to create a function for recursively generating iterative functions

I currently have some 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 that I would like the number of nested statements to vary depending on user input. If I wanted to create a function that generated an n number for statements like the above, how can I do this?

+5
source share
1 answer
 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 
+7
source

Source: https://habr.com/ru/post/1275656/


All Articles