传递值,而不是多发参数中的一个列表功能? [英] passing one list of values instead of mutiple arguments to a function?

查看:143
本文介绍了传递值,而不是多发参数中的一个列表功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说有一个函数 FUNC()这两个参数, A b 。是否有某种在Python技术通过一个单独的列表 MYLIST 其中既有价值观的作用呢?

Lets say there's a function func() which takes two arguments, a and b. Is there some kind of technique in Python to pass a single list mylist which has both values to the function instead?

def myfunc(a, b):
    return a+b

myfunc([1, 2])

如果一个是完全肯定,他总是调用同一个功能,并知道多少个参数需要,我们可以做这样的事情:

If one was completely sure that he was always calling the same function and knew how many arguments it takes, one could do something like this:

mylist = [1, 2]
a, b = mylist

myfunc(a, b)

但是,如果你有需要养活某些功能列表,每个人都有不同数量的参数?
人们可以写code为他的每个功能的不同行的名单解压到变量,并将它们传递到相应的功能,但如果Python有一些内置在传递一个列表,而不是单独的参数值(即当事先确定该列表具有价值的相应金额),那么这将看起来好多了,最重要的,需要code远不如线。

But what if you have lists you need to feed to certain functions, and each has different amount of arguments? One could write separate lines of code for each of his functions to unpack the lists into variables and pass them to the corresponding functions, but if Python has something built-in to pass a single list instead of individual argument values (when being sure beforehand that list has the corresponding amount of values), then that would look a lot better and most importantly would require far less lines of code.

推荐答案

您可以使用 * 来的解开列表分为参数的:

myfunc(*mylist)

这篇关于传递值,而不是多发参数中的一个列表功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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