简体   繁体   中英

Python populating input arguments for a function with *args

If I have a function which supports variable argument number, ie uses *args, how can I populate the arguments from a loop/list comprehension? Say the function expects multiple lists as arguments and I have a table/dataframe and want to use each column as an input argument, why does this not work?

funName([df[iCol].values for iCol in df.columns])

Say my dataframe has 5 columns, I would be required to call the function like so:

funName(col1, col2, col3, col4, col5)

But I do not want to manually create variables for each column but rather populate the argument list dynamically. Thanks.

Unpack your list when passing it in:

funName(*[df[iCol].values for iCol in df.columns])

List unpacking is required because if you don't, fn will get a single argument, which is a list, say [1, 2, 3] , and you want a sequence of arguments 1, 2, 3 .

For example:

>>> def fn(*args):
...     print args
...     
>>> fn([1, 2, 3])
([1, 2, 3],)
>>> fn(*[1, 2, 3])
(1, 2, 3)
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM