x = 5
l = [1]
for i in range(x):
print(l)
newlist = []
newlist.append(l[0])
for i in range(len(l) - 1):
newlist.append(l[i] + l[i+1])
newlist.append(l[-1])
l=newlist
上面的代码仅将我输出为直角三角形。
输出:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
但是我只想打印三角形的最后一级。但是我不知道如何实现。 请帮我解决一下这个。
所需输出:
[1, 4, 6, 4, 1]
Pull the
print()
call outside of the loop. And you actually need one less iteration to get the result, so changex
tox - 1
in thefor ...
line.Move the line
print(l)
to be outside of the for loop, to make sure you're only printing after it completes您正在循环内部进行打印,在每个要添加的元素之间进行打印。如果只想打印最终结果,请在循环后将打印内容移至。