【问题标题】:How to pass extra variable to function if conditions are met如果满足条件,如何将额外的变量传递给函数
【发布时间】:2020-07-08 16:28:23
【问题描述】:

假设我有以下 python 代码:

hp = 0
if 'header' is in paramdict.keys():
    hp = paramdict['header']
mydf = [pd.read_excel(xlsx, sheet, header = hp) for sheet in xlsx.sheet_names]

如果headerparamdict 中,我只想传递它。 (默认值为 0)

有没有更好的方法来做到这一点,或者更容易/占用更少空间的方法?我已经尝试过 fstrings 和 eval 但无法让它们工作。

【问题讨论】:

    标签: python python-3.x one-liner


    【解决方案1】:

    dict 有一个.get 方法,允许您传递一个默认值,如果keydict不存在

    ,则返回该值
    hp = paramdict.get('header', 0)
    mydf = [pd.read_excel(xlsx, sheet, header=hp) for sheet in xlsx.sheet_names]
    

    这是一个例子,

    >>> d = {'one': 1, 'two': 2}
    >>> d
    {'one': 1, 'two': 2}
    >>> d.get('one', 'Nope, not here')
    1
    >>> d.get('three', 'Nope, not here')
    'Nope, not here'
    

    【讨论】:

    • 太棒了!有没有办法在不知道默认值的情况下做到这一点? (理想情况下不调用任何默认值,以避免对具有许多可选参数的函数进行冗长且不可读的函数调用。)
    • 默认的默认值是None,也就是说,如果你不将第二个参数传递给get,它会在key不存在时返回None。如果您没有特定的默认值,恐怕您必须想出一些逻辑来处理这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多