python - 使用字符串格式创建二维列表

标签 python string formatting

假设输入“table”是字符串列表的列表,目标是创建并返回格式化的
表示二维表的字符串。

  • 二维表的每一行都在单独的行上;最后一行后面是一个空行
  • 每列均左对齐;
  • 各列之间用单个竖线“|”分隔;并且必须恰好有一个空格 竖线之前和之后;
  • 每行以竖线开始和结束;并且后面必须正好有一个空格 前导小节和结束小节之前

这是我得到的:

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

    return new_string

当行间距相等时,我的代码在某些情况下可以工作。例如:

input: [['A','BB'],['C','DD']]
output: '| A | BB |\n| C | DD |\n'
print:| A | BB |
      | C | DD |

但是,当行不相似时,例如:

input: [['10','2','300'],['4000','50','60'],['7','800','90000']]

它导致我的输出不同:

Right_output: '| 10   | 2   | 300   |\n| 4000 | 50  | 60    |\n| 7    | 800 | 90000 |\n'
my_output: '| 10 | 2 | 300 |\n| 4000 | 50 | 60 |\n| 7 | 800 | 90000 |\n'

正确的输出应该如下所示:

| 10   | 2   | 300   |
| 4000 | 50  | 60    |
| 7    | 800 | 90000 |

我的输出:

| 10 | 2 | 300 |
| 4000 | 50 | 60 |
| 7 | 800 | 90000 |

我需要在哪里修改代码才能使打印输出与正确的输出匹配?我猜这与列的最大宽度有关?

最佳答案

padding 的语法带有 str.format() 的字符串(左对齐)如下所示:

>>> '{:10}'.format('test')
'test      '

在打印表格之前,您需要预先计算列的宽度。这会产生正确的输出:

def show_table(table):
    new_string = ''

    widths = [max([len(col) for col in cols]) for cols in zip(*table)]

    for i in table:
        for j in range(len(i)):
            new_string += '| {:{}} '.format(i[j], widths[j])
        new_string += '|\n'

    return new_string

关于python - 使用字符串格式创建二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116706/

相关文章:

MYSQL - 插入连接字符串

python - JSON 解码字符串 - 未终止的字符串

javascript - 将值循环为特定格式

javascript - 在 JavaScript 中用前导零填充数字

python - Tensorflow Iris 数据集永远不会收敛

python - 使用 Scippy 的 ndimage.map_coordinates 进行插值时出现意外结果

java - For 循环遍历字符串并添加/替换字符

java - 如何打印格式化的 BigDecimal 值?

python - Pyramid 中的 Unicode hell : MySQL -> SQLAlchemy -> Pyramid -> JSON

python - 如何使用 numpy 对循环数组进行切片