没有重复和订购的号码表

2024-09-30 20:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码返回一个列表[0,0,0]到[9,9,9],它不产生重复,并且每个元素按从最小到最大的顺序排列。在

def number_list():
    b=[]
    for position1 in range(10):
        for position2 in range(10):
            for position3 in range(10):
                if position1<=position2 and position2<=position3:
                    b.append([position1, position2, position3])

    return b

正在寻找一种不使用多个变量(position1、position2、position3)而只使用一个变量i来编写这段代码的更短更好的方法。在

下面是我修改代码的尝试,但我一直在实现if语句:

^{pr2}$

Tags: and代码in元素number列表forif
3条回答

只需使用列表理解,一种方法:

 >>> [[x,y,z] for x in range(10) for y in range(10) for z in range(10) if x<=y and y<=z]
    [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4], [0, 0, 5], [0, 0, 6], 
[0, 0, 7], [0, 0, 8], [0, 0, 9], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 1, 5], [0, 1, 6], [0, 1, 7], [0, 1, 8], [0, 1, 9], [0, 2, 2], [0, 2, 3], 
[0, 2, 4], [0, 2, 5], [0, 2, 6], [0, 2, 7], [0, 2, 8], [0, 2, 9], [0, 3, 3], 
[0, 3, 4], [0, 3, 5], [0, 3, 6], [0, 3, 7], [0, 3, 8],....[6, 8, 8], [6, 8, 9], 
[6, 9, 9], [7, 7, 7], [7, 7, 8], [7, 7, 9], [7, 8, 8], [7, 8, 9], [7, 9, 9], 
[8, 8, 8], [8, 8, 9], [8, 9, 9], [9, 9, 9]]

这里有一种比检查更简单的方法,但在我看来,这比combinations_with_replacement更糟糕:

[(a, b, c) for a in range(10)
           for b in range(a, 10)
           for c in range(b, 10)]

也就是说,与在生产之后过滤值不同,您只需首先生成您想要的值。在

与另一个^{}答案相同的是,^{}还有另一种方法:

list(itertools.combinations_with_replacement(range(10), 3))

相关问题 更多 >