5

Python调用作为参数的函数的方法

 2 years ago
source link: https://blog.xpgreat.com/p/function_parameter_dict/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

今天在做project的时候遇到一个需求,简单来说是给定一个未知的函数func和他的参数范围,需要用这些参数重复调用该函数,记录返回值。此时遇到的问题是不知道func有多少参数和传入参数的顺序,查阅文档后发现可以用参数字典给函数传参,现记录于此。

给定一个函数func,参数名列表param_names,参数列表params,多次调用该函数并记录返回值。

def func(a, b, c):
  print(a, b, c)

param_names = ['a', 'b', 'c']
params = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]
res = []

for para in params:
  func(**dict(zip(param_names, para)))

# Output:
1, 2, 3
4, 5, 6
7, 8, 9

使用itertools.product快速循环生成参数表

params = itertools.product(*list(params.values()))

这里的params是一个字典,key是参数名字,value是参数可选范围,比如"param1" :[0, 1, 2]itertools.product可以接受多个list,需要用*list的形式解包传入参数。

Python

Licensed under CC BY-NC-SA 4.0


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK