Python 3.x 对于通过元组A的循环,将元组Ai的大小从N增加到i
我试图通过元素来迭代,其中list N返回一个迭代器,它遍历所有可能的元组A,其中Ai从0变为Ni。元素始终为和int。首选具有for循环和while循环的解决方案或解决方案路径Python 3.x 对于通过元组A的循环,将元组Ai的大小从N增加到i,python-3.x,list,for-loop,while-loop,tuples,Python 3.x,List,For Loop,While Loop,Tuples,我试图通过元素来迭代,其中list N返回一个迭代器,它遍历所有可能的元组A,其中Ai从0变为Ni。元素始终为和int。首选具有for循环和while循环的解决方案或解决方案路径 def f(*args): lst = [] for i in range(args[0]): for x in range(args[1]): for a in range(args[2]): for v in range(arg
def f(*args):
lst = []
for i in range(args[0]):
for x in range(args[1]):
for a in range(args[2]):
for v in range(args[3]):
lst.append((i,x,a,v))
return lst
print(f(5, 3, 1, 5))
这段代码可以工作,但我不想硬编码:假设我想输入另一个int,比如:
print(f(5,3,1,5,6))
你可以使用递归。它为循环替换未知数量的分层
def fr(tt, idx = 0):
lst = []
if idx == len(tt)-1: # last index, just loop
for x in range(tt[idx]):
lst.append(tt[:-1] + (x,))
return lst
for x in range(tt[idx]): # loop and call child loops
l2 = tt[:idx] + (x,) + tt[idx+1:] # update this index
lst.extend(fr(tuple(l2), idx+1)) # iterate next level
return lst
print(fr((5, 3, 1, 5)))
print(fr((5, 3, 1, 5, 6)))
输出
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 0, 3), (0, 0, 0, 4), ......., (4, 2, 0, 3), (4, 2, 0, 4)]
[(0, 0, 0, 0, 0), (0, 0, 0, 0, 1), (0, 0, 0, 0, 2), (0, 0, 0, 0, 3), ......., (4, 2, 0, 4, 4), (4, 2, 0, 4, 5)]
您可以为此使用递归。它为
循环替换未知数量的分层
def fr(tt, idx = 0):
lst = []
if idx == len(tt)-1: # last index, just loop
for x in range(tt[idx]):
lst.append(tt[:-1] + (x,))
return lst
for x in range(tt[idx]): # loop and call child loops
l2 = tt[:idx] + (x,) + tt[idx+1:] # update this index
lst.extend(fr(tuple(l2), idx+1)) # iterate next level
return lst
print(fr((5, 3, 1, 5)))
print(fr((5, 3, 1, 5, 6)))
输出
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 0, 3), (0, 0, 0, 4), ......., (4, 2, 0, 3), (4, 2, 0, 4)]
[(0, 0, 0, 0, 0), (0, 0, 0, 0, 1), (0, 0, 0, 0, 2), (0, 0, 0, 0, 3), ......., (4, 2, 0, 4, 4), (4, 2, 0, 4, 5)]
另一种方法是:
def f(*args):
res = [[]]
for z in map(range, args):
res = [tuple(x)+(y,) for x in res for y in z]
return res
f(5,3,1,5)
另一种方法是:
def f(*args):
res = [[]]
for z in map(range, args):
res = [tuple(x)+(y,) for x in res for y in z]
return res
f(5,3,1,5)
你打开了我的眼睛,让我有了一种新的思维方式。你打开了我的眼睛,让我有了一种新的思维方式。这很有魅力,而且解释得很好!工作就像一个魅力和良好的解释!