• Python 知识要点:多值参数


    定义支持多值参数的函数

    有时需要一个函数能够处理参数个数不确定,这是需要使用多值参数。

    Python中有两种多值参数:

    • 参数名前增加一个 * 可以接收元组
    • 参数名前增加一个 ** 可以接收字典

     

    【多值参数传递】

    def demo(num, *nums, **person):
        print(num)
        print(nums)
        print(person)
    
    
    demo(1)
    print("-" * 10)
    demo(1, 2, 3, 4, name="小麦", age=18)

    【多值参数求和】

    def tu_sum(*num):
        i = 0
        n = len(num)
        s = 0
        while i < n:
            s += num[i]
            i += 1
        print(s)
    
    
    tu_sum(1, 2, 100)

    【元组和字典的拆包】

    调用多值参数函数时,希望将一个元组变量或者字典变量,直接传递给参数,

    可以使用拆包,简化参数的传递,拆包的方式:

    • 在元组变量前增加一个 *
    • 在字典变量前增加两个 **
    def demo(*args, **kwargs):
        print(args)
        print(kwargs)
    
     
    # 元组变量/字典变量
    gl_nums = (1, 2, 3)
    gl_dict = {"name": "小麦", "age": 18}
    
    demo(*gl_nums, **gl_dict)
    从现在开始,种下梦想中的参天大树
  • 相关阅读:
    InnoDB in Mysql
    Store engine for Mysql
    Replication in Mysql
    Mysql note 3
    查看SQL对象的创建脚本
    Mysql note 2
    Jsp登录后数据采集奇怪的Apache服务器
    一行代码收集页
    使用Subsonic与ObjectDataSource(ODS)
    二分查找
  • 原文地址:https://www.cnblogs.com/dc2019/p/13173976.html
Copyright © 2020-2023  润新知