python - 让帕斯卡在多行中打印

标签 python list

我创建了 Pascal 的三角形,但它全部打印在一行上。关于如何让它打印成行(而不是三角形)有什么建议吗?

row=input("Please enter height: ")
triangle=[]
for rownum in range (0,row+1):
   newvalue=1
   newrow=[]
   if row==0:
       newrow.append(int(newvalue))

   elif row==1:
       newrow.append(int(newvalue,newvalue))

   else:

       for column in range(rownum):
         if column==0:
             newrow.append(1)
         elif column==(rownum-1):
             newrow.append(int(newvalue))
         else:
             new_value=triangle[rownum-1][column]+triangle[rownum-1][column-1]
             newrow.append(int(new_value))
   triangle.append(newrow)
print triangle

最佳答案

>>> print '\n'.join(' '.join(str(n) for n in row) for row in triangle)

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

或者,使用 str.center 来更好地对齐:

>>> print '\n'.join(' '.join(str(n) for n in row).center(80) for row in triangle)

                                       1                                        
                                      1 1                                       
                                     1 2 1                                      
                                    1 3 3 1                                     
                                   1 4 6 4 1                                    
                                 1 5 10 10 5 1                                  

要在更大比例下正确保留几何图形,您可以使用 str.format 技巧,如下所示:

>>> print '\n'.join(' '.join('{:3d}'.format(n) for n in row).center(80) for row in triangle)

                                        1                                       
                                      1   1                                     
                                    1   2   1                                   
                                  1   3   3   1                                 
                                1   4   6   4   1                               
                              1   5  10  10   5   1                             
                            1   6  15  20  15   6   1                           
                          1   7  21  35  35  21   7   1                         
                        1   8  28  56  70  56  28   8   1                       
                      1   9  36  84 126 126  84  36   9   1                     

关于python - 让帕斯卡在多行中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612531/

相关文章:

python - 在尊重括号的同时用逗号拆分列表中的字符串

python - 从列表中删除字典的重复项

python - 如何确保在 python 中的 qlistwidget 上新添加的项目可见?

python - 获取目录中每个文件的最后修改时间

c# - 删除列表中的重复对象 (C#)

python - 根据彼此之间的差异对列表元素进行分组

python - 我正在尝试获取所选列表项的索引值

java - PyYaml 到 SnakeYaml --- AWT-EventQueue- 0"Can' t 为标签 :yaml. org,2002:java/object 构造一个 java 对象:

python - Pandas :条件列创建

python - 无法通过python路径访问python文件