繁体   English   中英

Python:在 function 中传入一个元组作为参数

[英]Python: Passing in a tuple as an argument in a function

我正在使用np.select(condition, choices)Pandas DataFrame创建新列。 我想把我的代码模块化成一个function来实现,我比较麻烦的方法如下:

def selection(
    df: pd.DataFrame,
    conditions: Optional[List] = None,
    choices: Optional[List] = None,
    column_names: Optional[List] = None,
):
    if conditions is not None:  # if its none, then don't run this, implies choices and column names are none too
        for condition, choice, col_name in zip(conditions, choices, column_names):
            df[col_name] = np.select(condition, choice, default=" ")
    return df

要运行这个 function,我只需这样做:

conditions = [...]
choices = [...]
column_names = [...]
my_tuple = (conditions, choices, column_names)
df = selection(df, *my_tuple)

我想提高我的编码技能,我觉得这种方式不是最优的,特别是,我觉得我的 arguments 涉及conditions, choices, column_names可以是一个元组作为参数传入。 我欢迎任何关于改进此代码的建议。

如果你真的想将它们作为元组传递,是的,你可以:

def selection(
    df: pd.DataFrame,
    cond_choice_col: Optional[Tuple] = None
):
    if cond_choice_col is not None:  # if its none, then don't run this, implies choices and column names are none too

        # unpack the tuple here
        for condition, choice, col_name in zip(*cond_choice_col):
            df[col_name] = np.select(condition, choice, default=" ")
    return df

conditions = [...]
choices = [...]
column_names = [...]
my_tuple = (conditions, choices, column_names)

df = selection(df, cond_choice_col=my_tuple)

但老实说,我确实认为您的 function 比上面的更人性化。

In [53]: def foo(df, conditions=None, choices=None):
    ...:     print(df, conditions, choices)
    ...: 
In [54]: foo('df')
df None None

使用关键字,您可以使用字典提供 arguments:

In [55]: adict={'conditions':[1,2,3], 'choices':['yes','no']}
In [56]: foo('df', **adict)
df [1, 2, 3] ['yes', 'no']

或值的元组:

In [57]: foo('df', *adict.values())
df [1, 2, 3] ['yes', 'no']

有关参数语法和解包的更多信息:

https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM