0

I have a difficulty in printing a 2-D list into a nice table format. This is the expected output: Click to see the expected output This is the code I am using: Click to see my code The output I get is however not nicely presented, the spacing between each row element is not consistent: Click to see my output

Please help me with this issue. Thank you very much!

  • 1
    can you share the input data in the text format here? – Akash Ranjan Dec 12 '20 at 04:28
  • Please include the code as text in the question, not as an image. – Brian McCutchon Dec 12 '20 at 04:29
  • displayStock = [["No","Company","Cap","Qty","BoughtPrice","MarketPrice"],["1","Microsoft","Mega",100,188,207],["2","Amazon","Mega",5,1700,3003],["3","PayPal","Large",80,100,188],["4","Apple","Large",100,60,110],["5","Fastly","Mid",30,40,76],["6","Square", "Mid",30,40,178]] for x in displayStock: for y in x: print(y,"\t",end="") print() – Huang Yawen Dec 12 '20 at 04:48
  • The above is the code I am using, but it can't generate a nice tabular format ... – Huang Yawen Dec 12 '20 at 04:49

3 Answers3

0

you can use pandas dataframe here. It would print a nice tabular format of the data:

import pandas as pd
df = pd.DataFrame({'No.':'1st column data','company':'2nd column data'}) and so on.

The column data should be in a list format.

shekhar chander
  • 600
  • 8
  • 14
0

Try this:

import pandas as pd

display_stock = [
                ["No","Company", "Cap", "Qty", "BoughtPrice", "MarketPrice"],
                ["1","MS", "Large", 10, 43, 45],
                ["2","Amazon", "Large", 10, 43, 450],
                ["3","Small Co", "Small", 100, 10, 7]
            ]

df = pd.DataFrame( data = display_stock[1:] , columns = display_stock[0])

print(df.to_string(index=False))

Results into:

   No   Company    Cap  Qty  BoughtPrice  MarketPrice
   1        MS  Large   10           43           45
   2    Amazon  Large   10           43          450
   3  Small Co  Small  100           10            7
vbn
  • 274
  • 2
  • 7
0

There are many ways of solving this issue. As you can see from @shekaha's post, it is possible to use other libraries such as Pandas that will do the job for you. It appears that you are new to Python, so I suggest that you consider learning about how to do it yourself.

What follows is a very simple example of formatting. For a real application you will want to make things much more robust.

It is important to remember for your application that, when you print something, everything is ultimately converted into a string. Hence, if you want columns to "line up", you will need to make sure that the strings that represent each item in each column have the same length (including white spaces. Since your input has integers and strings, you will want to convert everything into a string first.

newData = [[str(v) for v in vs] for vs in displayStock]

Now, you will want to calculate the max length of each column. There are many ways of doing that. I'll do this in a couple of steps to make things simple:

lengths = [[len(v) for v in vs] for vs in newData]
maxLens = [max(lengths) for lengths in zip(*lengths)]

maxLens will give you the maximum lengths of each column. You will have to generate the proper texts with the right length that you want to print in each line. Here is an example of how you can do that

printStrs = [ ' '.join([ f'{v:{maxLens[i]}}' for i, v in enumerate(vs) ]) for vs in newData]
toPrint = '\n'.join( printStrs )

The last variable toPrint is something that you can use for printing the result.

Consider looking through the result and figure out how you will improve the results. For example, you may want to have different columns right- or left-justified. Try to figure out how you will do that.

ssm
  • 5,277
  • 1
  • 24
  • 42