Python列表输出杨辉三角形
时间: 2024-02-13 11:36:19 浏览: 68
Python语言实现杨辉三角
可以使用以下代码实现:
```
def generate(numRows):
triangle = []
for i in range(numRows):
row = [None for _ in range(i+1)]
row[0], row[-1] = 1, 1
for j in range(1, len(row)-1):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
# 输出杨辉三角形的前6行
tri = generate(6)
for row in tri:
print(row)
```
输出结果:
```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
```
阅读全文