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

时间:2019-02-05 09:33:37

标签: 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 个答案:

答案 0 :(得分:0)

def triangle(n):   
    k = 2*n - 2
    for i in range(0, n):   
        for j in range(0, k): 
            print(end=" ")  
        k = k - 1
        for j in range(0, i+1):  
            print("| ", end="") 
        print("\r")     
n = 5
triangle(n) 


this will return

D:\>st.py
        |
       | |
      | | |
     | | | |
    | | | | |

答案 1 :(得分:0)

将其拆分为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)

输出:

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

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