将多个参数传递给python中的函数的方法 [英] Way to pass multiple parameters to a function in python
问题描述
我已经编写了一个调用函数的python脚本.此函数将7个列表作为函数内的参数,如下所示:
I have written a python script which calls a function. This function takes 7 list as parameters inside the function, something like this:
def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse,
AlldaysHLFound_bse, AllvolumeFound_bse,
AllprevCloseFound_bse, AllchangePercentFound_bse,
AllmarketCapFound_bse):
,其中除link
以外的所有参数均为列表.但这使我的代码看起来很难看.我将这些列表传递给此函数,因为该函数在所有这些列表中附加了几个值.我该如何以更具可读性的方式为其他用户使用?
where all the arguments except link
are lists. But this makes my code looks pretty ugly. I pass these lists to this function because the function appends few values in all of these lists. How can I do it in more readable way for other users?
推荐答案
测试功能:
您可以使用由*args
表示的多个参数和由**kwargs
表示的多个关键字,并传递给函数:
You can use multiple arguments representing by *args
and multiple keywords representing by **kwargs
and passing to a function:
def test(*args, **kwargs):
print('arguments are:')
for i in args:
print(i)
print('\nkeywords are:')
for j in kwargs:
print(j)
示例:
然后使用任何类型的数据作为参数,并使用与函数关键字一样多的参数.该函数将自动检测它们并将它们分隔为参数和关键字:
Then use any type of data as arguments and as many parameters as keywords for the function. The function will automatically detect them and separate them to arguments and keywords:
a1 = "Bob" #string
a2 = [1,2,3] #list
a3 = {'a': 222, #dictionary
'b': 333,
'c': 444}
test(a1, a2, a3, param1=True, param2=12, param3=None)
输出:
arguments are:
Bob
[1, 2, 3]
{'a': 222, 'c': 444, 'b': 333}
keywords are:
param3
param2
param1
这篇关于将多个参数传递给python中的函数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!