【问题标题】:Using bound argument name inside python function在 python 函数中使用绑定参数名称
【发布时间】:2020-12-21 22:36:52
【问题描述】:

我目前在列中打印多个数组的黑客方式使用关键字参数来标记输出:

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)

使用过

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

生产

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

是否有另一种方法可以使用绑定的参数名称(例如 rho)并避免非关键字参数的重复(例如 rho=rho),以便可以简单地键入 table(rho,T=[665,240],Fx)?提前谢谢你。

【问题讨论】:

  • 我不认为 Python 有这样的速记。
  • 我怀疑如果有的话,它会实际上 hackish。 (就像检查堆栈帧并试图从接收到的对象中找出变量名。)
  • 除非您提前知道位置名称,否则不可能有任何实用的解决方案。如果您确实提前知道位置名称,或者有某种方法可以仅根据值来识别它们,那么也许。

标签: python function variable-binding


【解决方案1】:

使用 RHO=rho,其中 RHO 是输出中的标题。

替换

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

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

如果这不可接受,您将不得不接受第一个参数

替换

def table(**data_dict)

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

并调用如下:

替换

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

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

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2018-09-30
    相关资源
    最近更新 更多