0

My current hackish manner of printing multiple arrays in columns uses keyword arguments to label the output:

def table(**data_dict):
    n=([len(x) for x in data_dict.values()]) # # data for each var
    N=max(n)
    # prep data & print headings
    prntstr=''
    for i,var in enumerate(data_dict):
        # convert lists to str for printing, padding as needed
        data_dict[var] = ['{:.5g}'.format(x) for x in data_dict[var]] + ['']*(N-n[i]) 
        prntstr=prntstr+f'| {var:^8} |'
    print(prntstr,'-'*12*len(data_dict),sep='\n'); # print heading 
    # print data
    for i in range(0,N):
        prntstr=' '.join(f'{data_dict[var][i]:>11}' for var in data_dict)
        print(prntstr)

and used

rho=[1.5,0.11]
Fx=[-14.2]
table(rho=rho,T=[665,240],Fx=Fx)

producing

|   rho    ||    T     ||    Fx    |
------------------------------------
        1.5         665       -14.2
       0.11         240

Is there another way to do this that can use the bound argument name (e.g rho) and avoid the repetition (e.g. rho=rho) for non-keyword arguments so that one could type simply table(rho,T=[665,240],Fx)? Thank you in advance.

  • I don't think Python has a shorthand like that. – Barmar Dec 21 '20 at 22:40
  • I suspect if there is one, it's gonna be *actually* hackish. (Like inspecting the stack frames and trying to figure out variable names from the received objects.) – superb rain Dec 21 '20 at 22:59
  • Unless you know the positional names ahead of time, there's not likely any practical solution. If you do know the positional names ahead of time, or have some way to discern them based on the value alone, then maybe. – sytech Dec 21 '20 at 23:18

1 Answers1

-1

Use RHO=rho where RHO is the heading in the output.

Replace

table(rho=rho,T=[665,240],Fx=Fx)

with

table(RHO=rho,T=[665,240],Fx=Fx)

If this is not acceptable you will have to accept the first argument

Replace

def table(**data_dict)

with

def table(RHO, **data_dict):
    data_dict['rho'] = RHO

and call as follows:

Replace

table(rho=rho,T=[665,240],Fx=Fx)

with

table(rho,T=[665,240],Fx=Fx)
Aaj Kaal
  • 1,205
  • 1
  • 9
  • 8