如何使用 prettytable 模块 python 创建具有不同行数的 table

How to create a table with different number of rows using prettytable module python

我有以下代码使用 PrettyTable 生成 table:

from prettytable import PrettyTable 

# columns names
columns = ["Characters", "FFF", "Job"] 

# lists
lista1 = ["Leanord", "Penny", "Howard", "Bernadette", "Sheldon", "Raj"]
lista2 = ["X", "X", "X", "X", "X", "X", "X"]
lista3 = ["B", "C", "A", "D", "A", "B", "B"]
 
# init table 
myTable = PrettyTable() 
  
# Add data
myTable.add_column(columns[0], [item for item in lista1]) 
myTable.add_column(columns[1], [item for item in lista2]) 
myTable.add_column(columns[2], [item for item in lista3]) 

print(myTable)

这是输出:

但是,我真正想要的是创建一个具有不同列大小(我的列表具有不同长度)的 table。换句话说,这是我想要的输出:

我尝试使用上面的代码,但是,我收到以下错误:异常:列长度 7 与行数 6 不匹配!

非常感谢您的帮助!!!

通过用空字符串填充较短的列来保持所有列的大小相同。


from prettytable import PrettyTable


def column_pad(*columns):
  max_len = max([len(c) for c in columns])
  for c in columns:
      c.extend(['']*(max_len-len(c)))

# columns names
columns = ["Characters", "FFF", "Job"] 

# lists
lista1 = ["Leonard", "Penny", "Howard", "Bernadette", "Sheldon", "Raj","Amy"]
lista2 = ["X", "X", "X", "X"]
lista3 = ["B", "C", "A", "D", "A", "B"]

column_pad(lista1,lista2,lista3)
 
# init table 
myTable = PrettyTable() 
  
# Add data
myTable.add_column(columns[0], lista1) 
myTable.add_column(columns[1], lista2) 
myTable.add_column(columns[2], lista3) 

print(myTable)

+------------+-----+-----+                              
| Characters | FFF | Job |                              
+------------+-----+-----+                              
|  Leonard   |  X  |  B  |                              
|   Penny    |  X  |  C  |                              
|   Howard   |  X  |  A  |                              
| Bernadette |  X  |  D  |                              
|  Sheldon   |     |  A  |                              
|    Raj     |     |  B  |                              
|    Amy     |     |     |                              
+------------+-----+-----+