繁体   English   中英

Python:为二维数组创建可变格式字符串

[英]Python: create a variable format string for 2D Array

我目前正在阅读 Supercharged Python 这本书,有一个问题,我想尝试优化。 我想为可变大小的二维数组创建一个字符串 for.format。

def print_2dArray_opt(lst: list):
    width = 1
    row_string = '' 

    for r in lst:
        for c in r:
            temp = len(str(c))
            row_string = row_string + '{:{w}}' + ' ' 
            if temp > width:
                width = temp
        row_string = row_string + '\n'

    print(row_string.format(lst, w = width)) # That of course doesn't work


print_2dArray_opt([[1, 10, 100, 200],
                   [1, 10, 100, 200],
                   [1, 10, 100, 200],
                   [1, 10, 10000, 200]
                   ])

但我不知道如何制定该打印语句以便它可以工作。 有什么建议么?

试试这种格式风格

f'{c:{width}}'

所以固定代码:

def print_2dArray_opt(lst: list):
    width = 1
    row_string = '' 

    for r in lst:
        for c in r:
            temp = len(str(c))             
            if temp > width:
                width = temp

            row_string = row_string + (f'{c:{width}}').strip() + ' '

        row_string = row_string + "\n"

    print(row_string.strip())


print_2dArray_opt([[1, 10, 100, 200],
                [1, 10, 100, 200],
                [1, 10, 100, 200],
                [1, 10, 10000, 200]
                ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM