简体   繁体   English

如何将元素传入 For 循环以运行 function

[英]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).每个字符串都与父 package(在本例中为 QuantStats)的 function 相关。

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.由于某种原因, qs.stats.l 行不起作用。 I am not sure how to reference each element in the list, such that the qs function can run.我不确定如何引用列表中的每个元素,以便 qs function 可以运行。

Hopefully there is a simple work around?希望有一个简单的解决方法? Any thoughts would be very much appreciated:) thanks.任何想法将不胜感激:) 谢谢。

Use the getattr() function to get the defined function.使用 getattr() function 得到定义的 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: )我认为您输入 1 而不是i ,应该是( for i in List:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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