How to split list and pass them as separate parameter?

后端 未结 4 790
庸人自扰
庸人自扰 2020-12-05 06:52

My problem is I have values in a list. And I want to separate these values and send them as a separate parameter.

My code is:

def egg():
    return          


        
相关标签:
4条回答
  • 2020-12-05 07:12
    >>> argList = ["egg1", "egg2"]
    >>> egg2(*argList)
    egg1
    egg2
    

    You can use *args (arguments) and **kwargs (for keyword arguments) when calling a function. Have a look at this blog on how to use it properly.

    0 讨论(0)
  • 2020-12-05 07:16

    arg.split() does not split the list the way you want because the default separator does not match yours:

    In [3]: arg
    Out[3]: 'egg1, egg2'
    
    In [4]: arg.split()
    Out[4]: ['egg1,', 'egg2']
    
    In [5]: arg.split(', ')
    Out[5]: ['egg1', 'egg2']
    

    From the docs (emphasis added):

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

    0 讨论(0)
  • 2020-12-05 07:17

    There is a special syntax for argument unpacking:

    egg2(*argList)
    
    0 讨论(0)
  • 2020-12-05 07:25

    There are maybe better ways, but you can do:

    argList = ["egg1", "egg2"]
    (a, b) = tuple(argList)
    egg2(a, b)
    
    0 讨论(0)
提交回复
热议问题