Skip to content Skip to sidebar Skip to footer

How Can I Define Functions In A For Loop?

I'm trying to define a function of 3 unknown variables (k,m,c) but let's say I have to define it 100 times due to a different frequency f each time. Can I do this in a for loop in

Solution 1:

① You are nesting lists although you just want a flat list (of functions). See the answer of @BartoszKP on that.

② You want to create functions based on local variables. You can do this using lambdas, as @Harsh is proposing, or you can do it using defaulted variables:

defF_analytic(k, m, c, f=f):  # notice the f=f here!
    F_t = k*m*c*f 
    return F_t

③ You should consider whether having a list of functions really is what you want (as @Wooble already pointed out).

Solution 2:

No, what you have is a list of lists of functions, with each inner list having 1 function.

Replace

f_t.append([])
f_t[index].append(F_analytic)

with

f_t.append(F_analytic)

(Although honestly, this whole approach seems rather suspicious; any reason you don't want one function with 4 parameters instead of 100 with 3?)

Solution 3:

This is because you are creating a list of lists, you can call each function object like this:

f_t[0][0](1,2,3)

Alternatively, just create a list of functions:

f_t = []

for f in inputs[:,0]:
    index = index +1
    def F_analytic(k, m, c):
        F_t = k*m*c*f 
        return F_t
    f_t.append(F_analytic)

And as noted by other answers and comments, this all seems a rather strange approach. Do you really need to do this? :)

Solution 4:

Sorry i dont think i answered the question properly, try this approach:

f_t = []
for f in input[:,0]:
    f_t.append(lambda k, m, c: k*m*c*f)

You can call the functions easily by: lets say you want to call the first one:

f_t[0](k,m,c)

Where k,m,c are your variables

Solution 5:

Let's clean this code up:

#instead of an index counter, python provide `enumerate`# so that you can have the counter as part of your loop#index = -1
f_t = []
for index, f inenumerate(inputs[:,0]):
#   index = index +1defF_analytic(k, m, c):
      #these two lines are redundant. You're just returning an expression# so this whole function can be a lambda
      F_t = k*m*c*f 
      return F_t
   #why are you creating an inner list for each index position,# and then appending the function to it?#even if you wanted to have the inner list, you could do it in one step
   f_t.append([])
   f_t[index].append(F_analytic)

If we make the specified changes, we end up with:

f_t = [(lambda k, m, c: k*m*c*f) for f in inputs[:,0]]

Of course a much simpler approach would be simply to calculate the inputs to the product, including f, and multiply directly.

Post a Comment for "How Can I Define Functions In A For Loop?"