将一个值列表而不是多个参数传递给函数? [英] passing one list of values instead of mutiple arguments to a function?

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

问题描述

假设有一个函数 func(),它有两个参数,ab.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)

但是如果您有需要提供给某些函数的列表,并且每个列表都有不同数量的参数怎么办?可以为他的每个函数编写单独的代码行,将列表解包为变量并将它们传递给相应的函数,但是如果 Python 有内置的东西来传递单个列表而不是单个参数值(如果事先确定list 有相应数量的值),那么看起来会好很多,最重要的是需要更少的代码行.

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天全站免登陆