问题
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)
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.
回答1:
You can use *
to unpack the list into arguments:
myfunc(*mylist)
回答2:
def myfunc(a, b):
return a+b
mylist = [1, 2]
myfunc(*mylist)
Here mylist
can be list
, tuple
, string
etc of length 2.
来源:https://stackoverflow.com/questions/11064406/passing-one-list-of-values-instead-of-mutiple-arguments-to-a-function