Home > Back-end >  python Printing a list in a tabular format without modules
python Printing a list in a tabular format without modules

Time:05-29

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?

CodePudding user response:

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 |
  • Related