我正在尝试创建一个函数,该函数将接受输入x并为循环创建嵌套的x。这里有一个例子:
def looper(loop_amount, loop_value):
for n in range(loop_amount):
# Create a nested loop with loop_value.
looper(3, 5)
# Creates this:
for n in range(5):
for n in range(5):
for n in range(5):
一个可能的(尽管可能不是Python的(解决方案是使用递归:
def looper(loop_amount, loop_value):
if loop_value == 0:
# Code to be run in innermost loop
else:
for n in range(loop_amount):
looper(loop_value - 1)
这可以扩展为访问每个循环的索引,或者以某种方式具有返回值。
您可以使用itertools模块
import itertools
for tup in itertools.product(*(range(loop_value) for _ in range(loop_amount))):
# tup is a tuple of length loop_amount which will contain
# every combination of numbers between 0 and loop_value-1
您非常接近,希望这能有所帮助。
def loop(value):
for n in range(value):
def looper(loop_amount, loop_value):
for n in range(loop_amount):
loop(loop_value)