词典中的访问功能第2部分

编程入门 行业动态 更新时间:2024-10-28 03:29:36
本文介绍了词典中的访问功能第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

作为此问题的后续行动:我有2个功能看起来像这样:

As a follow-up to this question: I have 2 functions that look like this:

def abc(a,b): return a+b def cde(c,d): return c+d

而且想要将它分配给这样的字典:

And I want to assign it to a dictionary like this:

functions = {'abc': abc(a,b), 'cde': cde(c,d)}

我可以这样做,但是会在'cde ':

I could do this, but it would break at 'cde':

functions = {'abc':abc, 'cde':cde} functions_to_call = ['abc', 'cde'] for f in functions_to_call: a, b = 3, 4 c, d = 1, 2 if f in functions: functions[f](a, b)

另外,如果cde有3个参数呢?

Also, what if cde took 3 arguments?

推荐答案

使用 args 的单独序列,并使用splat运算符 * ):

Make a seperate sequence of args and use the splat operator (*):

>>> def ab(a,b): ... return a + b ... >>> def cde(c,d,e): ... return c + d + e ... >>> funcs = {'ab':ab, 'cde':cde} >>> to_call = ['ab','cde'] >>> args = [(1,2),(3,4,5)] >>> for fs, arg in zip(to_call,args): ... print(funcs[fs](*arg)) ... 3 12

更多推荐

词典中的访问功能第2部分

本文发布于:2023-10-19 15:10:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词典   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!