python定义函数可变参数_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!

Imagine my 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()

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)?

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

解决方案

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()

Example use case:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值