python - Python动态函数参数
问题描述
调用下面的函数时,我可以提供将使用的值而不是函数中的默认参数(见下文)。
cerebro.addstrategy(GoldenCross, fast=10, slow=25)
这对于少数已知参数非常有效,但我正在转向更复杂的系统。本质上,我需要传递一个 fast_1、fast_2、fast_3 等。这些参数的总量会发生变化(总是在 100 左右,但可能会有所不同)。是否有我可以编写的语句将动态添加 X 数量的参数到我的函数调用?
我尝试在函数调用中使用 for 语句,但收到语法错误。
解决方案
我从两个方面理解你的问题:
- 你想调用你的函数传递给它不同的参数(这是可选的),你可以像这样完成它:
def add(first, second=0, third=3):
return (first+second+third)
number_list = list(range(1, 200)) # Generates a list of numbers
result = [] # Here will be stored the results
for number in number_list:
# For every number inside number_list the function add will
# be called, sending the corresponding number from the list.
returned_result = add(1,second=number)
result.insert(int(len(result)), returned_result)
print(result) # Can check the result printing it
- 您希望您的函数处理任意数量的可选参数,因为您不知道如何确定它们有多少,您可以发送一个列表或参数,如下所示:
def add(first,*argv):
for number in argv:
first += number
return first
number_list = (list(range(1, 200))) # Generates a list of numbers
result = add(1,*number_list) # Store the result
print(result) # Can check the result printing it
在这里您可以找到有关 *args 的更多信息
推荐阅读
- ios - ViewController 未从 iOS 13.0 版本开始加载
- reactjs - 使用 Azure Devops 部署的 React 应用程序给出“您无权查看此目录或页面”
- c++ - 在 C++ 中从外部访问嵌套类
- sql-server - 基于另一个结果集的sql server查询结果
- php - 向该数组添加新数据
- angular - 在角度方面,有没有办法测试 .spec 测试中是否存在垫子错误?
- python - 将数据从 csv 导入 postgresql 时出现时间戳错误
- c# - 如何让我的所有表单都发生 TopMost?
- r - 保留列的最后一个值
- javascript - Digitalocean 使用 nginx 部署节点 https 应用程序