继续Can a variable number of arguments be passed to a function? 中的对话,我想学习如何在python 2.7中为函数生成随机数量的参数。
特别是,在循环各种类别时,我想将未知数量的 array_like (或 list s?)传递给scipy.stats.f_oneway
。< / p>
一个有效的简单例子是:
list_male = [34.316349, 34.32932, 34.27, 34.33905, 34.328951]
list_female = [34.61984, 34.34275, 34.6389, 34.44709, 34.51833]
f_oneway(list_male, list_female)
这可以产生
F_onewayResult(statistic=12.15815414713931, pvalue=0.0082363437299719927)
因为我知道我的类别gender
只有两个类male
,female
。
但是如果我运行多个类别的循环并且我不想预先确定特定列表呢?例如,如果animal
中的类别列pd.DataFrame
具有未知数量的类。我希望在循环中执行df['animal'].unique().tolist()
之类的操作,然后创建 array_like (或任何必需的)以提供给f_oneway
。
答案 0 :(得分:3)
我不熟悉f_oneway(...)
,但假设它可以采用可变数量的参数,并且你有可变数量的列表,你可以这样做:
list_male = [34.316349, 34.32932, 34.27, 34.33905, 34.328951]
list_female = [34.61984, 34.34275, 34.6389, 34.44709, 34.51833]
list_both = [...]
list_neither = [...]
list_of_lists = [list_male, list_female, list_both, list_neither]
f_oneway(*list_of_lists)
这是通过使用splat operator来完成的,它将列表内容解压缩为单个参数