Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

python - passing one list of values instead of mutiple arguments to a function?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use * to unpack the list into arguments:

myfunc(*mylist)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...