使用python语言实现将一个列表的数据输出为金字塔形状
时间: 2023-05-27 20:04:26 浏览: 150
一种基于C++实现的!金字塔型数据结构探讨
以下是使用Python实现将一个列表的数据输出为金字塔形状的代码:
``` python
def print_pyramid(n, lst):
"""
n: int - number of rows in the pyramid
lst: list - list containing the elements to print in pyramid
"""
# calculate the number of elements in the middle row
mid = n // 2 + 1
# iterate over each row in the pyramid
for i in range(1, n+1):
# calculate the number of spaces required to center the row
spaces = abs(mid - i)
# print the required spaces followed by the elements in the list
print(' ' * spaces + ' '.join(str(x) for x in lst[:i]))
# get the next set of elements from the list
lst = lst[i:]
# example usage
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
print_pyramid(n, lst)
```
输出:
```
1
2 3
4 5 6
7 8 9
```
阅读全文