Python:定义具有可变数量参数的函数

标签 python function class parameters

我不确定这个东西是否有名字,所以到目前为止我在网上找不到任何信息,尽管肯定有!

想象一下我的 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 个字典)加上其他参数,您只需要哪一个? (例如要绘制的项目或者可以是标题)?

实际上,我想创建一个函数(在我的 MWE 中),无论我向该函数输入多少个字典,它都能在给定共同标题和要绘制的项目的情况下,设法绘制该字典的给定项目

最佳答案

带星号 (*) 的解决方案

这将是 python 星号参数样式的完美案例,如下所示:

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)

前面的参数

如果您希望字典排在第一位,则其他参数必须仅为关键字:

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

并使用显式参数名称调用它

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

关于Python:定义具有可变数量参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45192234/

相关文章:

c - 从文件中精确打印和扫描 (C)

javascript - 如何仅传递非空变量作为函数参数?

javascript - 未捕获的类型错误 : Class constructor Hero cannot be invoked without 'new'

javascript - JS : TypeError: Class extends value <ClassName> is not a constructor or null

python - 导入时tftpy包语法错误

python - 在 Python 中将可变长度字符串拆分为变量的最佳方法是什么?

python - Pandas:将时间戳转换为 EST 时出现属性错误

python - 在Python(numpy)中迭代时间序列

c - 在 C 中如何将函数作为参数传递?

来自 XML 的 C# 类定义