简体   繁体   English

在python中打印具有对齐列的表格

[英]Print a table with aligned columns in python

I have a class Table with a tuple called header我有一个名为header的元组的类Table

self.header = ("Column_1", "Column_2", "Column_3", "Column_4", "Column_5")

and a dictionary of tuples called __entries that are added with the function:以及与函数一起添加的名为__entries的元组字典:

"""@brief Creates a new entry"""
def addEntry(self, column_1 : str , column_2 : str, column_3 : bool, column_4 : List[str], column_5 : Callable[[],None]) -> None:
    self.__entries[column_1] = (column_1, column_2, column_3, column_4, column_5)

I want to print the header and all entries as a formatted table.我想将标题和所有条目打印为格式化表格。 My current attempt is:我目前的尝试是:

"""@brief Print the header and all entries as a table"""
def print(self) -> None:
    print("|\t" + self.header[0] + "\t|\t" + self.header[1] + "\t|\t" + self.header[2] + "\t|\t" + self.header[3]+ "\t|" + self.header[4]+ "\t|")
    for key in self.__entries:
        entry = self.__entries[key]
        print("|\t" + entry[0] + "\t|\t" + entry[1] + "\t|\t" + str(entry[2]) + "\t|\t" + str(entry[3]) + "\t|\t" + str(entry[4])+ "\t|")

But obviously this doesn't resize the columns, and so the program:但显然这不会调整列的大小,因此程序:

def Foo() -> None:
    print(HelloWorld)

def Bar() -> None:
    print(HelloWorld)

def Baz() -> None:
    print(HelloWorld)

if __name__== "__main__":
    table = Table()
    table.addEntry("test","Craig",False,[], Foo)
    table.addEntry("test2","Bob",False,[], Bar)
    table.addEntry("test3","Bill",False,[], Baz)

    methodRegistry.print()

Outputs:输出:

|       Column_1        |       Column_2        |       Column_3        |       Column_4        | Column_5      |
|       test    |       Craig   |       False   |       []      |       <function Foo at 0x7f1192b56e18>        |
|       test2   |       Bob     |       False   |       []      |       <function Bar at 0x7f1191464730>        |
|       test3   |       Bill    |       False   |       []      |       <function Baz at 0x7f11914647b8>        |

I am new to python, but I imagine there is an easy way to do this without manually having to calculate the width of each row and adjust accordingly.我是 python 新手,但我想有一种简单的方法可以做到这一点,而无需手动计算每行的宽度并进行相应调整。

Full source code can be found here: https://gitlab.com/snippets/1936949完整的源代码可以在这里找到: https : //gitlab.com/snippets/1936949

I highly suggest you to convert your Table into a pandas Dataframe.我强烈建议您将Table转换为pandas Dataframe。 If you do so, obtaining a tabular representation of your table is easy using to_markdown :如果这样做,使用to_markdown可以轻松获取表格的表格表示:

# Generating a test table in pandas
df  = pd.DataFrame({'Column_2': {'test': 'Craig', 'test2': 'Bob', 'test3': 'Bill'},
 'Column_3': {'test': False, 'test2': False, 'test3': False},
 'Column_4': {'test': '[]', 'test2': '[]', 'test3': '[]'},
 'Column_5': {'test': '<function Foo at 0x7f9f898a0e18>',
  'test2': '<function Bar at 0x7f9f881ae730>',
  'test3': '<function Baz at 0x7f9f881ae7b8>'}})
df.index.name = 'Column_1'

# Printing the table in a nice tabular way:
print(df.to_markdown())
| Column_1   | Column_2    | Column_3    | Column_4    | Column_5                         |
|:-----------|:------------|:------------|:------------|:---------------------------------|
| test       | Craig       | False       | []          | <function Foo at 0x7f9f898a0e18> |
| test2      | Bob         | False       | []          | <function Bar at 0x7f9f881ae730> |
| test3      | Bill        | False       | []          | <function Baz at 0x7f9f881ae7b8> |

In general, all table operations are supported by pandas , which is why it is not recommended to build your own Table structure (unless this is part of some learning course).一般情况下, pandas支持所有表操作,这就是为什么不建议构建自己的Table结构(除非这是某些学习课程的一部分)。

Use a well know python package to print in tabular format.使用众所周知的 python 包以表格格式打印。 For example, you may use prettytable .例如,您可以使用prettytable You can install it with teh cmd pip install prettytable你可以用 teh cmd pip install prettytable安装它

>>> from prettytable import PrettyTable
>>> t = PrettyTable(hdrs)
>>>
>>> headers = ("Column_1", "Column_2", "Column_3", "Column_4", "Column_5")
>>> t = PrettyTable(headers)
>>> t.add_row(("test","Craig",False,[], 'Foo'))
>>> t.add_row(("test2","Bob",False,[], 'Bar'))
>>> t.add_row(("test3","Bill",False,[], 'Baz'))
>>> print(t)
+-----------+-----------+-----------+-----------+-----------+
| Column_1  | Column_2  | Column_3  | Column_4  | Column_5  |
+-----------+-----------+-----------+-----------+-----------+
|    test   |   Craig   |   False   |     []    |    Foo    |
|   test2   |    Bob    |   False   |     []    |    Bar    |
|   test3   |    Bill   |   False   |     []    |    Baz    |
+-----------+-----------+-----------+-----------+-----------+

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

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