python如何按设置次数自动生成嵌套的循环
lists是开始设置好的同时也设置了足够的空列表listX比如:lists=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,1...
lists是开始设置好的同时也设置了足够的空列表listX
比如:
lists=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
lists1=lists2=lists3=[]
假设一次循环是这样
for i in lists:
if i%2==0:
lists1=lists[:]
lists1.remove(i)
然后我随便设置一个循环次数,比如设置循环为n=3就出现如下的情况,要怎么做才能让循环中按照输入n的大小自动生成n次嵌套循环。(本人新手,这个例子是随便取的主要想知道python能不能实现这个想法)
for i in lists:
if i%2==0:
lists1=lists[:]
lists1.remove(i)
for i in lists1:
if i%3==0:
lists2=lists1[:]
lists2.remove(i)
for i in lists2:
if i%4==0:
lists3=lists2[:]
lists3.remove(i)
print(lists3)
exit() 展开
比如:
lists=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
lists1=lists2=lists3=[]
假设一次循环是这样
for i in lists:
if i%2==0:
lists1=lists[:]
lists1.remove(i)
然后我随便设置一个循环次数,比如设置循环为n=3就出现如下的情况,要怎么做才能让循环中按照输入n的大小自动生成n次嵌套循环。(本人新手,这个例子是随便取的主要想知道python能不能实现这个想法)
for i in lists:
if i%2==0:
lists1=lists[:]
lists1.remove(i)
for i in lists1:
if i%3==0:
lists2=lists1[:]
lists2.remove(i)
for i in lists2:
if i%4==0:
lists3=lists2[:]
lists3.remove(i)
print(lists3)
exit() 展开
1个回答
展开全部
嵌套可以实现这样的做法
lists=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def rl(lists, n):
for i in lists:
if i%(1+n)==0:
lists.remove(i)
print(n, lists)
if n > 1:
rl(lists[:], n-1)
rl(lists, 3)
可是为什么不简化一下
lists=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
lists1=lists[:]
for n in range(3):
for i in lists1:
if i%(2+n)==0:
lists1.remove(i)
print(lists1)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询