How to create a function for recursively generating iterating functions

假装没事ソ 提交于 2019-12-18 04:55:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/49059681/how-to-create-a-function-for-recursively-generating-iterating-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!