【笔记】python 中的 starred expression(星号表达式)功能:参数传递;用于unpacking可迭代的变量

注意: * (starred expression)不可以单独使用

正文:

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、语法参考

PEP 3132 – Extended Iterable Unpacking | peps.python.orghttps://www.python.org/dev/peps/pep-3132/PEP 448 – Additional Unpacking Generalizations | peps.python.orghttps://www.python.org/dev/peps/pep-0448/

猜你喜欢

转载自blog.csdn.net/nyist_yangguang/article/details/124607611