gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:03:24 25 4
gpt4 key购买 nike

假设输入“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com