将如何层叠表格制成表格

2024-03-28 21:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用制表法把两张表放在另一张表的旁边。你知道吗

我的方法:

test_table1 = tabulate([['Alice', 24], ['Bob', 19]])
test_table2 = tabulate([['Hans', 45], ['John', 38]])
master_headers = ["table1", "table2"]
master_table = tabulate([[test_table1, test_table2]],
                        master_headers, tablefmt="simple")
print(master_table)

但这会导致两个表都显示在表1的列中。你知道吗

请参见: enter image description here

问题:如何在python中级联表,最好使用tablate(或类似的库)?你知道吗

提前谢谢!你知道吗

马弗


Tags: 方法testmastertablesimplejohnheadersbob
1条回答
网友
1楼 · 发布于 2024-03-28 21:10:35

我真的不知道这是不是你得到的最好的选择,但这就是我想到的

test_table1 = str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines()
test_table2 = str(tabulate([['Hans', 45], ['John', 38]])).splitlines()
master_headers = ["table1", "table2"]
master_table = tabulate([list(item) for item in zip(test_table1,test_table2)],
                        master_headers, tablefmt="simple")
print(master_table)

输出:

table1     table2
    -      
  -          
Alice  24  Hans  45
Bob    19  John  38
  -          

解释:

其目的是将字符串数组传递给主表tabulate,就像测试表1测试表2一样

.splitlines()

>>>str(tabulate([['Alice', 24], ['Bob', 19]]))
>>>'  -   \nAlice  24\nBob    19\n  -   '
>>>str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines()
>>>['  -   ', 'Alice  24', 'Bob    19', '  -   ']

所以我们有[' - ', 'Alice 24', 'Bob 19', ' - '][' ', 'Hans 45', 'John 38', ' '],但是我们不能这样传递它们,因为输出会很奇怪:

table1     table2
    -      -      -      -
  -     Alice  24  Bob    19    -   
        Hans  45   John  38        

所以我们需要zip这些列表,并将值转换成list,因为zip返回listtuple对象,这里就是这样:

>>>[list(item) for item in zip(test_table1,test_table2)]
>>>[['  -   ', '     '],
   ['Alice  24', 'Hans  45'],
   ['Bob    19', 'John  38'],
   ['  -   ', '     ']]

这就是tabulate轻松获取数据并按您所需进行放置的方式。你知道吗

相关问题 更多 >