循环时可以使用哪个循环进行?
我想知道如何使用循环凝结此代码。这是(i)变量定义的重复序列(ii)时循环条件...(iii)变量增量
list_main = []
x1 = 1
while x1<= n:
x2 = x1
while x2 <= n:
x3 = x2
while x3 <= n:
#continue the sequence: x(i) = x(i-1) ; while x(i) <= n:
list_ = [x1,x2,...]
list_main.append(list_)
x3 = x3 + 1
x2 = x2 + 1
x1 = x1 + 1
我想要这样的东西:
max_x = 10 #maximum number of 'x's
#code
list_ = [x1,x2,x3,x4,x5,x6,x7,x8,x9,x10]
edit
如果'x的数字为2,而n为5 ,然后我所需的输出,即,list_main是
list_main = [[1,1],[1,2],[1,3],[1,4],[1,5],[2,2],[2,3],[2,4],[2,5],[3,3],[3,4],[3,5],[4,4],[4,5],[5,5]]
'x的数量为3,n为3,那么我所需的输出是
list_main = [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
I want to know how to condense this code using loops. It is a repeated sequence of (i) variable definition (ii) while loop condition ...(iii) variable increment
list_main = []
x1 = 1
while x1<= n:
x2 = x1
while x2 <= n:
x3 = x2
while x3 <= n:
#continue the sequence: x(i) = x(i-1) ; while x(i) <= n:
list_ = [x1,x2,...]
list_main.append(list_)
x3 = x3 + 1
x2 = x2 + 1
x1 = x1 + 1
I want something like this:
max_x = 10 #maximum number of 'x's
#code
list_ = [x1,x2,x3,x4,x5,x6,x7,x8,x9,x10]
Edit
If Number of 'x's is 2 and n is 5, then my desired output, i.e., list_main is
list_main = [[1,1],[1,2],[1,3],[1,4],[1,5],[2,2],[2,3],[2,4],[2,5],[3,3],[3,4],[3,5],[4,4],[4,5],[5,5]]
If the number of 'x's is 3 and n is 3, then my desired output is
list_main = [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如这个答案,您的问题可以这样解决:
As pointed out in this answer, your problem can be solved like this: