在python中向函数传递多个参数的方法

2024-05-19 01:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个调用函数的python脚本。此函数将7个列表作为函数内的参数,如下所示:

def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, 
                AlldaysHLFound_bse, AllvolumeFound_bse, 
                AllprevCloseFound_bse, AllchangePercentFound_bse, 
                AllmarketCapFound_bse):

其中除了link之外的所有参数都是列表。但这让我的代码看起来很难看。我将这些列表传递给该函数,因为该函数在所有这些列表中都附加很少的值。我怎样才能让其他用户更容易阅读呢?


Tags: 函数脚本列表参数deflinkbse调用函数
3条回答

测试功能:

可以使用表示为*args的多个参数和表示为**kwargs的多个关键字并传递给函数:

def test(*args, **kwargs):
    print('arguments are:')
    for i in args:
        print(i)

    print('\nkeywords are:')
    for j in kwargs:
        print(j)

示例:

然后使用任意类型的数据作为参数,使用任意多的参数作为函数的关键字。函数将自动检测它们并将它们分离为参数和关键字:

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

如果不需要为列表使用名称,可以使用*args

def WorkDetails(link, *args):
    if args[0] == ... # Same as if AllcurrValFound_bse == ...
        ...

 # Call the function:
 WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, AlldaysHLFound_bse, AllvolumeFound_bse, AllprevCloseFound_bse, AllchangePercentFound_bse, AllmarketCapFound_bs)

或者你可以用字典

def WorkDetails(link, dict_of_lists):
    if dict_of_lists["AllcurrValFound_bse"] == ...
        ...

# Call the function
myLists = {
    "AllcurrValFound_bse": AllcurrValFound_bse,
    "AllyearlyHLFound_bse": AllyearlyHLFound_bse,
    ...,
    ...
}
WorkDetails(link, myLists)

您可以将其更改为:

def WorkDetails(link, details):

然后将其调用为:

details = [ AllcurrValFound_bse, AllyearlyHLFound_bse, 
            AlldaysHLFound_bse, AllvolumeFound_bse, 
            AllprevCloseFound_bse, AllchangePercentFound_bse, 
            AllmarketCapFound_bse ]
workDetails(link, details)

您可以通过以下方法从细节中获取不同的值:

AllcurrValFound_bse = details[0]
AllyearlyHLFound_bse = details[1]
...

details转换为字典(变量名作为键)会更健壮,因此在多行代码和防御编程之间进行选择

相关问题 更多 >

    热门问题