【问题标题】:How to check if a function input is given or not?如何检查是否给出了函数输入?
【发布时间】:2018-07-30 17:00:35
【问题描述】:

请考虑这个接受两个参数的函数:seriescategorical_values。它的目标是获得一个series,使其分类,然后将原始系列的每个元素与分类的对应元素一起打印。但是,如果 categorical_values 已经作为输入传递给函数,则跳过分类阶段,函数只打印传递的 seriescategorical_values 对。

def my_function(series, categorical_values = None):

    if categorical_values: #meant to mean "if this argument is passed, just use it"
        categorical_values = categorical_values

    else: #meant to mean "if this argument is not passed, create it"
        categorical_values= pd.qcut(series, q = 5)

    for i,j in zip(series, categorical_values):
        print(i, j)

但是,在下面传递categorical_values

my_function(series, pd.qcut(series, q = 5))

导致:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

导致此错误的代码行是第一行:if categorical_values:

检查函数参数是否已通过的正确方法是什么?

【问题讨论】:

    标签: python python-3.x pandas function


    【解决方案1】:

    因为默认是无,你应该检查它不是那个。

    if categorical_values is not None:
        ...
    

    但是 if 块无论如何都是无操作的;倒过来会更好:

    if categorical_values is None:
        categorical_values = pd.qcut(series, q = 5)
    

    而且你根本不需要 else 块。

    【讨论】:

    • 该死。我什至试过categorical_values != None。现在我看到它应该是categorical_values is not None,因为在前一种情况下,它试图将categorical_values 中的每个元素与None 进行比较,从而引发该错误。谢谢
    • @Saeed 这就是为什么你应该使用is 而不是==None 的原因之一。除了很小的风格和性能问题外,类还可以覆盖 == 以返回不能在 if 条件下使用的 bool 数组。
    猜你喜欢
    • 2017-03-08
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多