Python:使用可变数量的参数定义一个函数 [英] Python: defining a function with variable number of arguments

查看:363
本文介绍了Python:使用可变数量的参数定义一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这东西是否有名称,因此尽管可以肯定,但到目前为止我在网上找不到任何信息!

I am not sure if this thing has a name, so I couldn't find any information online so far, although surely there is!

想象一下我的MWE:

def PlotElementsDict(dictionary1, dictionary2, itemToPlot, title):
    # dictionary 1 and dictionary 2 are collections.OrderedDict with 'key':[1,2,3]
    # i.e. there values of the keys are lists of numbers
    list1 = [dictionary1[key][itemToPlot] for key in dictionary1.keys()]
    list2 = [dictoinary2[key][itemToPlot] for key in dictionary2.keys()]
    plt.plot(list1, label='l1, {}'.format(itemToPlot)
    plt.plot(list2, label = 'l2, {}'.format(itemToPLot')
    plt.legend()
    plt.title(title)
    return plt.show()

如何创建一个函数(该函数甚至更笼统,我也希望对一个类也可以做到这一点),该函数需要使用一定数量的某种类型的参数(例如n个字典)加上您只需要一个的其他参数? (例如item to plot或可能是title)?

How can I create a function (but my question is even more general, I would like to be able to do this for a class as well) which takes a variable number of parameters of a certain type (for example n dictionaries) plus other parameters which you need only one? (for instance item to plot or could be title)?

在实践中,我想创建一个函数(在我的MWE中),无论我输入多少个字典,该函数都可以根据给定的公共标题和要绘制的项目来绘制该词典的给定项目

In practice I would like to create a function (in my MWE) that no matter how many dictionaries I feed into the function, it manages to plot the given items of that dictionary given a common title and item to plot

推荐答案

带星号(*)的解决方案

对于python的星号参数样式,这将是一个完美的例子,像这样:

Solution with asterisk (*)

This would be a perfect case for pythons asterisk argument style, like so:

def PlotElementsDict(itemToPlot, title, *dictionaries):
    for i, dct in enumerate(dictionaries):
        lst = [dct[key][itemToPlot] for key in dct]
        plt.plot(lst, label='l{}, {}'.format(i, itemToPlot))

    plt.legend()
    plt.title(title)
    plt.show()

用例示例:

dct1 = {'key' : [1,2,3]}
dct2 = {'key' : [1,2,3]}
dct3 = {'key' : [1,2,3]}

title = 'title'

itemToPlot = 2

PlotElementsDict(itemToPlot, title, dct1, dct2, dct3)

前面的参数

如果您希望字典排在首位,则其他参数只能是关键字:

Arguments in front

If you want the dictionaries to come first, the other arguments have to be keyword only:

def PlotElementsDict(*dictionaries, itemToPlot, title):
    pass

并使用显式参数名称进行调用

And call it with explicit argument names

PlotElementsDict(dct1, dct2, dct3, itemToPlot=itemToPlot, title=title)

这篇关于Python:使用可变数量的参数定义一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆