Python 星号表达式(starred expression)

ref: https://blog.csdn.net/DawnRanger/article/details/78028171

Python 星号表达式(starred expression)

*expression的作用

1、用于参数传递

出现在函数中,*args用于将传入的可迭代参数解析出来,并存入到args中

def f(*args, **kwargs):
    print(args)
    print(kwargs)
  • *会将传入的参数放入名为args的元组中
  • ** 会将传入的参数放入名为kwargs的字典中
>>> def f(a, b, c):
...   print a, b, c
...
>>> f(1, 2, 3)
1 2 3
>>> f(*['a', 'b', 'c'])
a b c
>>> f(3, *[1, 2])
3 1 2

2、用于unpacking可迭代的变量

将序列中的部分内容打包至一个列表中

  • example 1
python3
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a, *b, c = range(10)
>>> a
0
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
>>> c
9
  • example 2
>>> record = ('alice', 50, 1322,45, (12, 18, 2018))
>>> name, *_1, (*_2, year) = record
>>> name
'alice'
>>> _1
[50, 1322, 45]
>>> _2
[12, 18]
>>> year
2018
  • example 3
>>> for a, *b in [(1,2,3,4,5), ('a', 'b', 'c', 'hehe')]:
...     print(b, type(b))
...
[2, 3, 4, 5] <class 'list'>
['b', 'c', 'hehe'] <class 'list'>
  • 递归求和
>>> def sum(items):
...   head, *tail = items
...   return head + sum(tail) if tail else head
...
>>> sum([1, 3, 5, 7, 9])
25

注意:星号表达式(*expressoin)不可单独使用

# 以下实验结果在python3.x中
>>> *a = range(5)
  File "<stdin>", line 1
SyntaxError: starred assignment target must be in a list or tuple
>>> *a, = range(5)
>>> a
[0, 1, 2, 3, 4]

>>> a = *range(5)
  File "<stdin>", line 1
SyntaxError: can't use starred expression here
>>> a = *range(5),
>>> a = , *range(5)
  File "<stdin>", line 1
    a = , *range(5)
        ^
SyntaxError: invalid syntax

3、语法参考

  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值