【问题标题】:How to enter parameters to function in form of a list or a tuple?如何以列表或元组的形式输入参数以发挥作用?
【发布时间】:2014-01-20 22:54:48
【问题描述】:

是否可以以列表的形式输入函数的参数。 例如 -

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

好的,我得到了答案,但只是一个附加问题,仅与此相关 - 这是我的代码 -

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)

我收到此错误 -

 SyntaxError: only named arguments may follow *expression

请帮帮我。

【问题讨论】:

    标签: python list function parameters


    【解决方案1】:

    您可以使用 splat 运算符unpack the sequence(*):

    path = os.path.join(*my_list)
    

    演示:

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

    更新:

    要回答你的新问题,一旦你在参数中使用了*,你就不能传递位置参数,你可以在这里做这样的事情:

    from itertools import chain
    
    def func(*args):
        print args
    
    func(1, 2, *chain(range(5), [2]))
    #(1, 2, 0, 1, 2, 3, 4, 2)
    

    并且不要使用list作为变量名

    【讨论】:

    • 嘿,Ashwini 你能帮我解决我的新问题吗
    • @Anurag-Sharma 一旦你使用了*,你就不能传递位置参数。所以,file_name*sub_directories 之后抛出错误。
    • @Anurag-Sharma 你可以在那里使用itertools.chainos.path.join("applications", appname, *chain(sub_directories,[file_name]))
    【解决方案2】:

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

    path = os.path.join(*list) 
    

    【讨论】:

      【解决方案3】:

      您可以使用*-运算符来unpack the arguments

      举例

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

      'a/b'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 2013-02-28
        • 2019-11-18
        • 1970-01-01
        • 2018-12-09
        • 2015-03-25
        • 1970-01-01
        相关资源
        最近更新 更多