我已经在Python中写了一个功能,该功能采用了三个输入变量。现在,我想在每个输入变量的项目列表中调用该功能。因此,函数调用就是这样:
call_function('cat', 'brown', 2)
列表是:
category_list = ['cat', 'dog', 'squirrel']
color_list = ['brown', 'black']
age = [1,2,3]
现在我想在每个项目上运行函数。因此,它应该返回猫,棕色和1个,然后返回猫,棕色和2个,然后猫,棕色和3,然后猫,黑色和1个,然后猫,黑色和2个,然后猫,黑色和3然后为狗做同样的事情,然后对松鼠做同样的事情。我知道我需要循环调用该功能,但是我尝试并失败了几次。有人可以帮我吗?
I have written a function in python which takes three input variables. Now I want to call the function on a list of items for each input variables. So the function call is like this:
call_function('cat', 'brown', 2)
The lists are:
category_list = ['cat', 'dog', 'squirrel']
color_list = ['brown', 'black']
age = [1,2,3]
Now I want to run function on each item. So it should return results for cat, brown and 1, and then cat, brown and 2, and then cat, brown and 3 and then cat, black and 1, and then cat, black and 2, and then cat, black and 3 and then do the same for dog and then for squirrel. I know that I will need to call the function in a loop, but I tried and failed several times. Could someone please help me with this?
发布评论
评论(3)
使用
itertools
,它为您完成了工作,调用product
函数真的很容易。将变量提供给
itertools.product(....))
作为参数然后
list()
响应。代码
输出
证明
测试在这里

iTertools方法的代码
use
itertools
, it does the job for you, really simple to call theproduct
function.supply the variables to
itertools.product(....))
as paramatersthen
list()
the response.Code
Output
Proof
Test Here

code for method from itertools
这是使用pd.apply的另一种方法,使用itertools.product
结果:
如果函数命名为my_function
here is another way to do it, using pd.apply, after creating a dataframe using itertools.product
RESULT:
if function is named MY_FUNCTION
我通过在循环中调用函数来解决它。我确定有一种更高效/优雅的方法可以做到这一点,但是由于我的DF和列表很小,因此效果很好。想为那些正在处理小列表并遇到类似问题的人发布我的解决方案。当然,欢迎改进建议。
I solved it by calling the function in a loop. I am sure there is a more efficient/elegant way to do this, but since my df and lists are small, it works good. Wanted to post my solution for those who are working with small lists and having similar problem. Of course, improvement suggestions are welcome.