Home > other >  How to print two different type objects in python
How to print two different type objects in python

Time:07-11

I have Two object:

total_statuses = 10
status = {"A":2, "B":5, "C":3}

I want to print them in a simple table style without using any extra library such as tabulate.

Total    A   B    C
-------------------
 10      2   5    3

headers = ["Total"]   list(statuses.keys())
[print(f"{h:15}", end='') for h in header]

What is the effecient way to achieve this output?

CodePudding user response:

Here is a possible solution:

total_statuses = 10
status = {"A":2, "B":5, "C":3}

l1 = max(5, len(str(total_statuses)))   4
l2 = len(str(status['A']))   3
l3 = len(str(status['B']))   3
l4 = len(str(status['C']))
lines = [
    'Total    '.ljust(l1)   'A'.ljust(l2)   'B'.ljust(l3)   'C'.ljust(l4),
    '-' * (l1   l2   l3   l4),
    str(total_statuses).ljust(l1)   str(status['A']).ljust(l2)   str(status['B']).ljust(l3)   str(status['C']).ljust(l4),
]
print(*lines, sep='\n')

Output:

Total    A   B   C
------------------
10       2   5   3

CodePudding user response:

Another solution is use a function:

In [9]: def show(headers, statuses):
   ...:     [print(f"{h:15}", end='') for h in headers]
   ...:     print('\n'   '-' * (15 * len(statuses) 1))
   ...:     print(f'{str(sum(statuses.values())):15}', end='')
   ...:     for _, v in sorted(statuses.items()):
   ...:         print(f'{str(v):15}', end='')
   ...:     print()
   ...:

Output:

In [10]: show(headers, statuses)
Total          A              B              C
----------------------------------------------
10             2              5              3
  • Related