循环时可以使用哪个循环进行?

发布于 2025-01-22 09:30:35 字数 859 浏览 0 评论 0原文

我想知道如何使用循环凝结此代码。这是(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水染的天色ゝ 2025-01-29 09:30:35

这个答案,您的问题可以这样解决:

max_x = 10
n = 5
values = []
i = 1
while i <= n:
    list_values.append(i)
    i = i + 1
count = [max_x] * n
list_main = list(unique_combinations_from_value_counts(values,count,max_x))

As pointed out in this answer, your problem can be solved like this:

max_x = 10
n = 5
values = []
i = 1
while i <= n:
    list_values.append(i)
    i = i + 1
count = [max_x] * n
list_main = list(unique_combinations_from_value_counts(values,count,max_x))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文