如何在python中以对齐的方式打印动态2D列表? [英] how to print dynamic 2D list in an aligned manner in python?

查看:38
本文介绍了如何在python中以对齐的方式打印动态2D列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个列表,同时保持其元素垂直对齐.目前我的代码打印列表 [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]]

0 1 2 34 5 6 78 9 10 1112 13 14 15

相反,我想打印

 0 1 2 34 5 6 78 9 10 1112 13 14 15

如何在不导入任何内容的情况下实现这样的结果?这是我到目前为止编写的代码:

for i in BoardSize:打印(*i, end="\n")

解决方案

也许 tabulate 包适合您的需求.

来源:https://github.com/astanin/python-tabulate

这里有一个例子:

from tabulate import tabulate板尺寸 = [[0, 1, 2, 3],[4, 5, 6, 7],[8, 9, 10, 11],[12、13、14、15]]打印(制表(BoardSize,tablefmt =普通"))

输出:

 0 1 2 34 5 6 78 9 10 1112 13 14 15

无包编辑

快速而肮脏的解决方案

BoardSize = [[0, 1, 2, 3],[4, 5, 6, 7],[8, 9, 10, 11],[12、13、14、15]]max_number_of_digits = 0对于 BoardSize 中的行:对于行中的单元格:number_of_digits = len(str(cell))如果 number_of_digits >max_number_of_digits:max_number_of_digits = number_of_digits对于 BoardSize 中的行:打印行 = ''对于行中的单元格:# 填充字符串左侧的空格# 填充必须至少比# max_number_of_digits# 添加的数字越大,填充越宽print_row += f'{cell}'.rjust(max_number_of_digits + 1, ' ')打印(打印行)

I want to print a list while keeping its elements vertically aligned. Currently my code prints the list [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]] as

0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

Instead, I would like to print

 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

How can I achieve such a result without import anything? This is the code I've written so far:

for i in BoardSize:
    print(*i, end="\n")

解决方案

Maybe the package tabulate suits your needs.

Source: https://github.com/astanin/python-tabulate

Here an example:

from tabulate import tabulate

BoardSize = [
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [8, 9, 10, 11],
    [12, 13, 14, 15]]

print(tabulate(BoardSize, tablefmt="plain"))

Output:

 0   1   2   3
 4   5   6   7
 8   9  10  11
12  13  14  15

Edit without a package

A quick and dirty solution

BoardSize = [
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [8, 9, 10, 11],
    [12, 13, 14, 15]]


max_number_of_digits = 0
for row in BoardSize:
    for cell in row:
        number_of_digits = len(str(cell))
        if number_of_digits > max_number_of_digits:
            max_number_of_digits = number_of_digits


for row in BoardSize:
    print_row = ''
    for cell in row:
        # fill with space on the left side of the string
        # the padding has to be at least one higher than
        # the max_number_of_digits
        # the higher the number you add, the wider the padding
        print_row += f'{cell}'.rjust(max_number_of_digits + 1, ' ')

    print(print_row)

这篇关于如何在python中以对齐的方式打印动态2D列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆