【问题标题】:Use string format create a 2D list使用字符串格式创建二维列表
【发布时间】:2016-07-07 02:46:48
【问题描述】:

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

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

【问题讨论】:

  • AFAICS 您的输出确实满足要求,而您想要的输出不满足要求(在一些竖线之前有多个空格)。现在,如果您仍然想要其他输出,那么是的,您需要先计算每列的宽度,然后在格式化每个字符串时使用它。这意味着遍历输入两次,我认为您无法避免它。

标签: python string formatting


【解决方案1】:

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

【讨论】:

  • 非常感谢,您的代码完全有意义。小错误是 new_string += '| {{:>{}}} '.format(widths[j]).format(i[j])。我认为 '>' 使每一列都向右对齐。我将其更改为“
  • @markzzzz:对,> 向右对齐。要向左对齐,您可以省略它(我已经更新了帖子)。
【解决方案2】:

为了获得您想要的输出,我将表格元素的最大宽度集成到您的函数中:

def show_table(table):
    max_widths = map(max, map(lambda x: map(len, x), zip(*table)))
    new_string = '' 
    for i in table: 
        for j in range(len(i)):
            line = i[j]
            line = line + ' '*(max_widths[j]-len(line)) 
            new_string += '| {} '.format(line)
        new_string += '|\n'

    return new_string

解释 max_widths 线...

max_widths = map(max, map(lambda x: map(len, x), zip(*table)))

...可以分三步完成:

  1. 转置表格的行和列

    transposed = zip(*table)
    
  2. 获取所有字符串的长度以进行比较

    lengths = map(lambda x: map(len, x), transposed)
    
  3. 获取每列的最大长度

    max_widths = map(max, lengths)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多