2017-02-23 90 views
1

继续Can a variable number of arguments be passed to a function? 中的对话,我想了解如何为python 2.7中的函数生成随机数量的参数。为python函数生成未知数量的列表

特别地,虽然遍历各种类别,我想传递的一个未知的号码array_like(或列表 S')到scipy.stats.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] 
f_oneway(list_male, list_female) 

这个作品产生

F_onewayResult(statistic=12.15815414713931, pvalue=0.0082363437299719927) 

,因为我知道我的gender类只有两个班malefemale

但是如果我正在运行多个类别的循环并且我不想预先确定具体的列表呢?例如,如果pd.DataFrame中的类别列animal具有未知数量的类别。我希望在循环内执行类似df['animal'].unique().tolist()的操作,然后创建array_like(或任何需要的),以提供给f_oneway

+1

'f_oneway(* a_list_of_lists)'会起作用吗?你可以试试'a_list_of_lists = [list_male,list_female]'。 – 9000

+0

是的,精美的作品,谢谢! – elzurdo

回答

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,它将列表内容解压缩为单个参数