简体   繁体   中英

call functions from python list one by one and run multiple times for one function

We have list that contains functions and in for loop iteration i need to call them.

list1 = ['f1(agr1,agr2)', 'f2(arg1)', 'f3(arg1,arg2,agr3)']

for i in list1:
   i

This is not executing.

When i used like below :

for i in list1:
   i()

Getting below error:

TypeError: 'str' object is not callable

Other one is I need to use function arguments in different list and use zip in for loop or how do i pass arguments

Please help

Your first item is a string, as it says in the error. Your function needs to actually specify the functions:

list1 = [(f1, (arg1, arg2)),
         (f2, (arg1,)),
         (f3, (arg1, arg2, arg3))]

for i in list1:
    i[0](*i[1])

Currently you are listing not the functions themselves, but the output returned by calling them.

I'm not sure of your use case, so this might not be the best way at all to achieve what you actually want, but this slightly messy solution should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM