1

Continuing the conversation in Can a variable number of arguments be passed to a function? , I'd like to learn how to generate a random number of arguments for a function in python 2.7.

In particular, while looping over various categories, I would like to pass an unkown number of array_like (or lists?) to scipy.stats.f_oneway.

A simple example that works would be:

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)

This works yielding

F_onewayResult(statistic=12.15815414713931, pvalue=0.0082363437299719927)

because I knew that my category gender has only two classes male, female.

But what if I am running a loop of many categories and I do not want to predetermine specific lists? E.g, if a category column animal in a pd.DataFrame has an unknown number of classes. I would like within the loop to do something like df['animal'].unique().tolist() and then create array_like (or whatever required) to feed to f_oneway.

2
  • 2
    Would f_oneway(*a_list_of_lists) work? You can try with a_list_of_lists = [list_male, list_female]. Commented Feb 23, 2017 at 16:08
  • Yep, works beautifully, thanks! Commented Feb 23, 2017 at 16:10

1 Answer 1

4

I'm unfamiliar with f_oneway(...), but assuming that it can take a variable number of arguments, and that you have a variable number of lists, you can do this:

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)

This is accomplished with the use of the splat operator, which unpacks the list contents into individual arguments

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.