python中 *和 **的用法

这篇主要探讨 ** 和 * 前缀运算符,**在变量之前使用的*and **运算符.

简单示例:

>>> numbers = [2, 1, 3, 4, 7]
>>> more_numbers = [*numbers, 11, 18]
>>> print(*more_numbers, sep=', ')
2, 1, 3, 4, 7, 11, 18

用途:

  1. 使用 * 和 ** 将参数传递给函数
  2. 使用**和**捕获传递给函数的参数
  3. 使用*只接受关键字参数
  4. 使用*元组拆包过程中捕获项目
  5. 使用*解包iterables到一个列表/元组
  6. 使用**要解压缩词典到其他字典

例子解释:

  1. 调用函数时,*可以使用运算符将​​可迭代对象解压缩为函数调用中的参数:

    >>> fruits = ['lemon', 'pear', 'watermelon', 'tomato']
    >>> print(fruits[0], fruits[1], fruits[2], fruits[3])
    lemon pear watermelon tomato
    >>> print(*fruits)
    lemon pear watermelon tomato
    

    该print(*fruits)行将fruits列表中的所有项目print作为单独的参数传递到函数调用中,而我们甚至不需要知道列表中有多少个参数。

  2. ** 运算符允许我们采取键值对的字典,并把它解压到函数调用中的关键字参数。

    >>> date_info = {'year': "2020", 'month': "01", 'day': "01"}
    >>> filename = "{year}-{month}-{day}.txt".format(**date_info)
    >>> filename
    '2020-01-01.txt'
    

    ** 将关键字参数解包到函数调用中并不是很常见。我最常看到的地方是练习继承时:super()通常要同时包含*和**。
    双方*并 **可以在函数调用中多次使用,像Python 3.5的。

    >> fruits = ['lemon', 'pear', 'watermelon', 'tomato']
    >>> numbers = [2, 1, 3, 4, 7]
    >>> print(*numbers, *fruits)
    2 1 3 4 7 lemon pear watermelon tomato
    **多次使用类似:
    
    >>> date_info = {'year': "2020", 'month': "01", 'day': "
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值