Reputation: 709
I'd like to display two tables next to another using tabulate.
My approach:
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)
But this results in both tables being displayed in the column of table1.
Question: How can i cascade tables in python, preferably using tabulate(or a similar library)?
Thanks in advance!
Muff
Upvotes: 3
Views: 636
Reputation: 23494
I don't really know if this is the best choice that you get, but that's what i came up with
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)
Output:
table1 table2
--------- --------
----- -- ---- --
Alice 24 Hans 45
Bob 19 John 38
----- -- ---- --
Explanation:
The purpose was to pass array of strings to master_table's tabulate
, like it was done with test_table1 and test_table2
With .splitlines()
>>>str(tabulate([['Alice', 24], ['Bob', 19]]))
>>>'----- --\nAlice 24\nBob 19\n----- --'
>>>str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines()
>>>['----- --', 'Alice 24', 'Bob 19', '----- --']
So we had ['----- --', 'Alice 24', 'Bob 19', '----- --']
and ['---- --', 'Hans 45', 'John 38', '---- --']
, but we can't pass them that way, because output would be quite strange:
table1 table2
--------- --------- --------- ---------
----- -- Alice 24 Bob 19 ----- --
---- -- Hans 45 John 38 ---- --
So we needed to zip
those lists, and convert values to list
, because zip
return list
of tuple
objects, that's what happened here:
>>>[list(item) for item in zip(test_table1,test_table2)]
>>>[['----- --', '---- --'],
['Alice 24', 'Hans 45'],
['Bob 19', 'John 38'],
['----- --', '---- --']]
And that is the way how tabulate
easily will get data and put as you desired.
Upvotes: 1