I have data that is collected in a loop and stored under separate lists that hold only the same datatypes (e.g. only strings, only floats) as shown below:
names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]
I have treated these lists as "columns" of a table and wish to print them out as a formatted table that should look something like this:
Names | Weights | Costs | Unit_Costs
----------|---------|-------|------------
bar | 0.05 | 2.0 | 40.0
chocolate | 0.1 | 5.0 | 50.0
chips | 0.25 | 3.0 | 12.0
I only know how to print out data from lists horizontally across table rows, I have looked online (and on this site) for some help regarding this issue, however I only managed to find help for getting it to work in python 2.7 and not 3.5.1 which is what I am using.
my question is:
how do I get entries from the above 4 lists to print out into a table as shown above.
Each item index from the lists above is associated (i.e. entry[0] from the 4 lists is associated with the same item; bar, 0.05, 2.0, 40.0).
Two columns, separated by tabs, joined into lines. Look in itertools for iterator equivalents, to achieve a space-efficient solution. import string def fmtpairs(mylist): pairs = zip(mylist[::2],mylist[1::2]) return '\n'. join('\t'.
Here is a small implementation that does what you want in basic python (no special modules).
names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]
titles = ['names', 'weights', 'costs', 'unit_costs']
data = [titles] + list(zip(names, weights, costs, unit_costs))
for i, d in enumerate(data):
line = '|'.join(str(x).ljust(12) for x in d)
print(line)
if i == 0:
print('-' * len(line))
Output:
names |weights |costs |unit_costs
---------------------------------------------------
bar |0.05 |2.0 |40.0
chocolate |0.1 |5.0 |50.0
chips |0.25 |3.0 |12.0
Some interesting table draw with texttable
.
import texttable as tt
tab = tt.Texttable()
headings = ['Names','Weights','Costs','Unit_Costs']
tab.header(headings)
names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]
for row in zip(names,weights,costs,unit_costs):
tab.add_row(row)
s = tab.draw()
print (s)
Result
+-----------+---------+-------+------------+
| Names | Weights | Costs | Unit_Costs |
+===========+=========+=======+============+
| bar | 0.050 | 2 | 40 |
+-----------+---------+-------+------------+
| chocolate | 0.100 | 5 | 50 |
+-----------+---------+-------+------------+
| chips | 0.250 | 3 | 12 |
+-----------+---------+-------+------------+
You can install texttable
with using this command pip install texttable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With