Search code examples
pythonscipyeval

Python - Using string as expression (exec and eval not working)


I am trying to use scipy.stats.f_oneway() to perform ANOVA. It takes array_like as input, whatever that means.

numpy: formal definition of "array_like" objects?

Anyway, it works when I manually type in the data to be compared. For example, this works: Input:

list1 = [3,4,5,6]
list2 = [4,5,6,7]
list3 = [5,6,7,8]
sp.stats.f_oneway(list1, list2, list3)

Output:

F_onewayResult(statistic=2.3999, pvalue=0.1461)

However, I want to compare a lot of different lists and I would like to compare them dynamically in my code.

This is what I want:

list1 = [3,4,5,6]
list2 = [4,5,6,7]
list3 = [5,6,7,8]
listOfLists = [list1, list2, list3]
sp.stats.f_oneway(listOfLists)

However, f_oneway does not like this format of input. So I was thinking, maybe I could use a loop to create a string, then unpack it to use as the argument, like this:

list1 = [3,4,5,6]
list2 = [4,5,6,7]
list3 = [5,6,7,8]
listString = 'list1, list2, list3'
sp.stats.f_oneway(eval(listString))

However, this doesn't work. This leads me to believe this function requires input like:

sp.stats.f_oneway(list1, list2, list3)

How can I use a string to supply the input required by the f_oneway function?


Solution

  • you can do this:

    sp.stats.f_oneway(*listOflists)
    

    This will unwrap the list and puts in 3 individual arguments