gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:46:41 25 4
gpt4 key购买 nike

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

想象一下我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com