Iterable Unpacking 迭代解包

Python allows a tuple (or list) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the * operator) from an iterable on the right side of the assignment. The * is the iterable unpacking operator.
Syntax:
tuple/list of variables = any iterable object
(To create a tuple, we don’t need to use (), this also works for iterable unpacking)

Examples:
  1. When we need to pack multiple values into one single variable, we use a trailing comma, because the left side of the assignment must be a tuple (or a list)
    >> *a, = [1,2]
    >> a
    [1,2]
    
  2. The starred expression will be assigned a list of multiple values.
    >> *a, b = 1,2,3
    >> type(a)
    list
    
  3. We can’t use more than one starred expression in the assignment.
  4. We can merge the iterables using the * operator.
    >> a = [1,2]
    >> [0, *a, 3]
    [0, 1, 2, 3]
    
    Similarly,
    >> a = (i for i in range(5)) # generator is an iterable
    >> b = (i for i in range(5))
    >> list(a) == [*b]
    True
    
  5. Dictionary
    * unpack keys of a dictionary
    >> a ={1:'a', 2:'b'}
    >> [0, *a, 3] # unpack keys
    [0, 1, 2, 3]
    
    ** is called the dictionary unpacking operator
    >>letters = {"a": "A", "b": "B"}
    >> vowels = {"a": "a", "e": "e"}
    >> {**letters, **vowels}
    {'a': 'a', 'b': 'B',  'e': 'e', }
    
  6. Packing and Unpacking in Functions.
    python函数参数

Ref1: Unpacking in Python: Beyond Parallel Assignment
Ref2: PEP 3132 – Extended Iterable Unpacking

可能会重新修改下思路
PEP 448 – Additional Unpacking Generalizations

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值