Python expressions asterisk (starred expression)

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

Python expressions asterisk (starred expression)

*expressionRole of

1, for transmission parameters

Appear in the function, * args for incoming iteration parameters can be parsed and stored in the args

def f(*args, **kwargs):
    print(args)
    print(kwargs)
  • *It will be passed arguments in the tuple named args
  • ** The parameters will be passed into the dictionary is named 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, for unpacking may be a variable iteration

The part of the sequence to a packing list

  • 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'>
  • Recursive summation
>>> def sum(items):
...   head, *tail = items
...   return head + sum(tail) if tail else head
...
>>> sum([1, 3, 5, 7, 9])
25

Note : An asterisk expression (* expressoin) can not be used alone

# 以下实验结果在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, reference grammar

Published 63 original articles · won praise 52 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_41521681/article/details/103528136