Tabulate - How to Cascade tables
<p>I'd like to display two tables next to another using tabulate.</p>

<p>My approach:</p>

<pre><code>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)
</code></pre>

<p>But this results in both tables being displayed in the column of table1.</p>

<p>See:
<a href="http://i.stack.imgur.com/9eh9l.png" rel="nofollow"><img src="http://i.stack.imgur.com/9eh9l.png" alt="enter image description here"></a></p>

<p><strong>Question:</strong> How can i cascade tables in python, preferably using tabulate(or a similar library)?</p>

<p>Thanks in advance!</p>

<p>Muff</p>

<p>I don't really know if this is the best choice that you get, but that's what i came up with</p>

<pre><code>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)
</code></pre>

<p>Output:</p>

<pre><code>table1     table2
---------  --------
-----  --  ----  --
Alice  24  Hans  45
Bob    19  John  38
-----  --  ----  --
</code></pre>

<p><strong>Explanation</strong>:</p>

<p>The purpose was to pass array of strings to <em>master_table</em>'s <code>tabulate</code>, like it was done with <em>test_table1</em> and <em>test_table2</em></p>

<p>With <code>.splitlines()</code></p>

<pre><code>&gt;&gt;&gt;str(tabulate([['Alice', 24], ['Bob', 19]]))
&gt;&gt;&gt;'-----  --\nAlice  24\nBob    19\n-----  --'
&gt;&gt;&gt;str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines()
&gt;&gt;&gt;['-----  --', 'Alice  24', 'Bob    19', '-----  --']
</code></pre>

<p>So we had <code>['-----  --', 'Alice  24', 'Bob    19', '-----  --']</code> and <code>['----  --', 'Hans  45', 'John  38', '----  --']</code>, but we can't pass them that way, because output would be quite strange:</p>

<pre><code>table1     table2
---------  ---------  ---------  ---------
-----  --  Alice  24  Bob    19  -----  --
----  --   Hans  45   John  38   ----  --
</code></pre>

<p>So we needed to <code>zip</code> those lists, and convert values to <code>list</code>, because <code>zip</code> return <code>list</code> of <code>tuple</code> objects, that's what happened here: </p>

<pre><code>&gt;&gt;&gt;[list(item) for item in zip(test_table1,test_table2)]
&gt;&gt;&gt;[['-----  --', '----  --'],
   ['Alice  24', 'Hans  45'],
   ['Bob    19', 'John  38'],
   ['-----  --', '----  --']]
</code></pre>

<p>And that is the way how <code>tabulate</code> easily will get data and put as you desired.</p>

python python-3.x