Skip to main content
 首页 » 编程设计

python之函数 def show_table 创建并返回表示二维表的格式化字符串

2024年10月24日24grandyang

在我的代码中,我在间距方面遇到了麻烦,并且还找到了一种方法来确定每列的长度,这样我就知道何时换行。 列用单个竖线“|”分隔;并且必须恰好有一个空格 竖线前后; o 每行以竖线开始和结束;并且在之后必须恰好有一个空格 前导栏和结束栏之前 这是我到目前为止的代码:

def show_table(table): 
    string = ''  
    for i in table:  
        for j in range(len(i)): 
            line = i[j] 
            string += "{}".format(line) + "|" 
 
    return "|" + string +"\n" 

有一个限制:您必须使用字符串格式,% 或 .format()。 以下是列表列表的示例 这是一个例子:

>>> show_table([['A','BB'],['C','DD']]) 
'| A | BB |\n| C | DD |\n' 
>>> print(show_table([['A','BB'],['C','DD']]))  
| A | BB | 
| C | DD | 

请您参考如下方法:

您的代码非常接近,但是竖线周围没有适当的空格,并且您没有处理表格中每一行的末尾。

您不必担心列的宽度,因为您的作业描述说在列表项和竖线之间恰好放置一个空格。

这是您的代码的修复版本,更改最少。

def show_table(table): 
    string = ''  
    for i in table:  
        for j in range(len(i)): 
            line = i[j] 
            string += '| {} '.format(i[j]) 
        string += '|\n' 
 
    return string 
 
print(show_table([['A','BB'],['C','DD']]))     

输出

| A | BB | 
| C | DD | 

直接迭代列表比使用列表索引间接迭代更符合 Pythonic。

def show_table(table): 
    string = ''  
    for line in table:  
        for item in line: 
            string += '| {} '.format(item) 
        string += '|\n' 
 
    return string 

更紧凑的方法是使用列表理解:

def show_table(table): 
    return ''.join(['| {} |\n'.format(' | '.join(row)) for row in table])