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

2024-05-01 22:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的职责是:

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 
    |
   | |

 | | | |

Tags: in编辑forisdefrange数组array
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)

输出:

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

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

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 | | | | | | | | | | | | | | |

相关问题 更多 >