此代码返回列表[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
语句:
def number_list(): b=[] for i in range(1000): b.append(map(int, str(i).zfill(3))) return b
tijko.. 12
在与其他itertools
答案相同的说明中,还有另一种方法combinations_with_replacement
:
list(itertools.combinations_with_replacement(range(10), 3))
Iron Fist.. 7
只需使用列表理解,一种方法:
>>> [[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]]
Veedrac.. 5
这是比检查更简单的方法,但仍然比IMO更糟糕combinations_with_replacement
:
[(a, b, c) for a in range(10) for b in range(a, 10) for c in range(b, 10)]
也就是说,不是在生产后过滤值,而是仅在第一时间生成所需的值.
在与其他itertools
答案相同的说明中,还有另一种方法combinations_with_replacement
:
list(itertools.combinations_with_replacement(range(10), 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]]
这是比检查更简单的方法,但仍然比IMO更糟糕combinations_with_replacement
:
[(a, b, c) for a in range(10) for b in range(a, 10) for c in range(b, 10)]
也就是说,不是在生产后过滤值,而是仅在第一时间生成所需的值.