美文网首页
python变长参数列表

python变长参数列表

作者: 1直领悟不够 | 来源:发表于2019-04-07 10:11 被阅读0次

    语法:

    def function(*args):
            statements
    

    *args出现在参数列表中时,意味着传入的所有参数都将塞入一个列表中,而你在函数定义中使用args来引用这个列表。

    示例:

    def print_them_out(*args):
            for thing in args:
                    print(thing,'\t')
    

    如果要用连字符分割打印出来的参数,可像下面这个更精巧的示例那样做:

    def print_them_out(*args):
        my_str = '--'.join(args)
        print(my_str)
    
    >>print_them_out('John','Frank','lena','Bob')
    John--Frank--lena--Bob
    

    完整语法:

    def function(fixed_args,*args):
            statements
    

    这种语法表明,你可以在参数列表开头包含任意数量的“固定”参数。调用函数时,实参被赋给相应的固定参数(fixed_args),知道用完了所有固定参数。对于所有未赋给固定参数的实参,将它们都塞进args表示的列表中。

    def print_them_out(n, *args):
        print("There are",n,"band menmbers.")
        my_str = '--'.join(args)
        print(my_str)
    
    >>print_them_out(4,'John','Frank','lena','Bob')
    There are 4 band menmbers.
    John--Frank--lena--Bob
    

    就上述示例而言,一种更简单更可靠的方法是直接计算列表的长度,而不是增加一个参数。

    def print_them_out(*args):
        print("There are",len(args),"band menmbers.")
        my_str = '--'.join(args)
        print(my_str)
    

    相关文章

      网友评论

          本文标题:python变长参数列表

          本文链接:https://www.haomeiwen.com/subject/jhvjiqtx.html