简体   繁体   English

如何以列表或元组的形式输入参数?

[英]How to enter parameters to function in form of a list or a tuple?

Is it possible to enter the parameters of function in form of a list. 是否可以以列表的形式输入函数的参数。 For example - 例如 -

list1 = ["somethin","some"]
def paths(list):
    import os
    path = os.path.join() #I want to enter the parameters of this function from the list1
    return path

Okay i got my answer but just an aditional question, related to this only - here is my code - 好的,我得到了我的答案,但只是一个附加问题,仅与此相关 - 这是我的代码 -

def files_check(file_name,sub_directories):
    """
        file_name :The file to check
        sub_directories :If the file is under any other sub directory other than the   application , this is a list.
    """
    appname = session.appname
    if sub_directories:
        path = os.path.join("applications",
                        appname,
                        *sub_directories,
                         file_name)
        return os.path.isfile(path)
    else:
         path = os.path.join("applications",
                        appname,
                        file_name)
         return os.path.isfile(path)

i am getting this error - 我收到此错误 -

 SyntaxError: only named arguments may follow *expression

Please help me . 请帮我 。

You can unpack the sequence using the splat operator( * ): 您可以使用splat运算符( *解压缩序列

path = os.path.join(*my_list)

Demo: 演示:

>>> import os
>>> lis = ['foo', 'bar']
>>> os.path.join(*lis)
'foo\\bar'

Update: 更新:

To answer your new question you cannot pass positional arguments once you've used * in arguments, you can do something like this here: 要回答你的新问题,一旦你在参数中使用了*就不能传递位置参数,你可以在这里做类似的事情:

from itertools import chain

def func(*args):
    print args

func(1, 2, *chain(range(5), [2]))
#(1, 2, 0, 1, 2, 3, 4, 2)

And don't use list as a variable name 并且不要使用list作为变量名

只需使用*运算符解压缩列表

path = os.path.join(*list) 

You can use the *-operator to unpack the arguments . 您可以使用* -operator来解压缩参数

For Example 例如

data = ['a','b'] os.path.join(*data)

Gives

'a/b'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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