Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python Printing a list in a tabular format without modules

I have a list called entryList which begins empty, but as the user is prompted for input this input is added to the list. After 2 runs the list will look something like this:
[2, 1234, 'E', 2.0, 2.71, 6, 0800, 'U', 2.34, 20.89]
with each iteration of asking for input adding 5 values to the list. When this list is printed, I need it to look something like this:

EntryNo  PumpNo  Time  FType  LPrice  FAmount
---------------------------------------------
1        2       1234  E      2.00    2.71 
2        6       0800  U      2.34    20.89 

How can I get the list to print like this, with the EntryNo column increasing by 1 for each new row added, without importing any modules?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With some print and some formatting

values = [2, '1234', 'E', 2.0, 2.71,
          6, '0800', 'U', 2.34, 20.89]

cols = ["EntryNo", "PumpNo", "Time", "FType", "LPrice", "FAmount"]
print(*cols)
print("-" * len(" ".join(cols)))  # optional

for idx, i in enumerate(range(0, len(values), 5), start=1):
    print("{:<7d} {:<6d} {:<4s} {:<5s} {:<6.2f} {} ".format(idx, *values[i:i + 5]))
EntryNo PumpNo Time FType LPrice FAmount
----------------------------------------
1       2      1234 E     2.00   2.71 
2       6      0800 U     2.34   20.89 

With module pandas

You can use pandas, you’ll easily have an nice output, with to_markdown for example

import pandas as pd

values = [2, '1234', 'E', 2.0, 2.71,
          6, '0800', 'U', 2.34, 20.89]

df = pd.DataFrame([[idx, *values[i:i + 5]] for idx, i in enumerate(range(0, len(values), 5), start=1)],
                  columns=["EntryNo", "PumpNo", "Time", "FType", "LPrice", "FAmount"])

print(df.to_markdown(index=False))
|   EntryNo |   PumpNo |   Time | FType   |   LPrice |   FAmount |
|----------:|---------:|-------:|:--------|---------:|----------:|
|         1 |        2 |   1234 | E       |     2    |      2.71 |
|         2 |        6 |   0800 | U       |     2.34 |     20.89 |
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading