这段代码返回一个列表[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
语句:
只需使用列表理解,一种方法:
这里有一种比检查更简单的方法,但在我看来,这比
combinations_with_replacement
更糟糕:也就是说,与在生产之后过滤值不同,您只需首先生成您想要的值。在
与另一个^{} 答案相同的是,^{} 还有另一种方法:
相关问题 更多 >
编程相关推荐