python - 为打印到循环的每个字符串放置一个数组

标签 python python-3.x

我希望能够将每个 | 插入一个数组

这是我的功能:

def pyramide(lines):
    k = 1 * lines - 1 
    for i in range(0, lines): 
        for j in range(0, k): 
            print(end=" ") 
            k = k - 1
         for j in range(0, i+1): 
            print("|", end=" ") 
            print("\r")

lines = 5
pyramide(lines)

我尝试过:

for j in range(0, i+1): 
    each = print("|", end=" ") 
    array.push(each)
    print("\r")

但它似乎没有将其添加到数组中,我的问题是如何将每个 | 插入数组中,以便稍后删除它

编辑:

预期输入:

pyramide(5)

预期输出:

    |
   | |
  | | |
 | | | |

然后我应该能够从每行中删除 |

 stickDelete(3, 2) # first paramater is the line, second is how much | would like to delete 
    |
   | |

 | | | |

最佳答案

将其分成 2:

  • 包含“|”的数组列表的(或其他字符)
  • 打印“金字塔”数组的函数

封装在一个类中,你会得到类似的东西:

class CPyramide(object):

    def __init__(self, lines):
        self.pir = []
        # construct the array of arrays for the pyramid
        # each one holding the n-bars for a row
        for i in range(lines):
            # construct the array using a listcomprehension
            bars = ['|' for j in range(i+1)]
            self.pir.append(bars)

    def __str__(self):
        """print the pyramid"""
        o = ""
        # loop through all the rows that represent the pyramid
        # and use enumerate to have them numerical from 0 to len(pir)
        for i, L in enumerate(self.pir):
            # spaces decrease with increase of rows ...
            spaces = (len(self.pir) - i) * ' '
            # so, a line starts with the n-spaces
            o += spaces
            # appended with the bars of that row all in L
            o += ' '.join(L)
            # and a newline, which is definitely something else
            # then '\r' (on unix \r will show only one line when
            # using '\r'!)
            o += "\n"

        return o

    def stickDelete(self, line, n):
        self.pir[line] = self.pir[line][n:]


print("===============")
cpir = CPyramide(5)
print(cpir)
cpir.stickDelete(3, 2)
print(cpir)

输出:

===============
     | 
    | | 
   | | | 
  | | | | 
 | | | | | 

     | 
    | | 
   | | | 
  | | 
 | | | | | 

关于python - 为打印到循环的每个字符串放置一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54531287/

相关文章:

python - 缺少标签的深度多任务学习

python - 如何进一步过滤ResultSet的结果?

python - 如何在 Pycharm "Python Console"中运行代码?

Python - os.rename() - OSError : [WinError 123]

python - 如何在整个程序的生命周期中唯一标识Python中的类

python - 使用带有浮点值的列表运算符 "in"

python - 在 Python 中,将异常记录到文件的最佳方式是什么?

python - PyQuery Python 不支持 for 循环

python - 尽管属性存在,为什么 hasattr 会引发 ValueError ?

python - 如何将列表项附加到数据框中的特定列?