简体   繁体   中英

How to pass in element into For-loop to run a function

It's been a while since I have asked a questions but I am needing help with what I think is a simple task.

I have a list of string values which I have passed into a loop. Each one of the strings pertains to a function of a parent package (in this case, QuantStats).

Code appears as follows:

import QuantStats as qs
list = ['avg_loss', 'avg_gain', 'best']

for l in list:
(>>) print(l)
(>>) print(qs.stats.l(df['returns']) (Error here - 'l' not recognised. no output)

For some reason the qs.stats.l line does not work. I am not sure how to reference each element in the list, such that the qs function can run.

Hopefully there is a simple work around? Any thoughts would be very much appreciated:) thanks.

Use the getattr() function to get the defined function. Like this:

import QuantStats as qs
list = ['avg_loss', 'avg_gain', 'best']

for l in list:
(>>) print(l)
(>>) print(getattr(qs.stats,l)(df['returns'])

I think you entered 1 instead of i , It should be ( for i in List: )

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