打开包装清单

时间:2014-05-23 14:00:12

标签: python

解压缩到元组之间Python有什么区别:

x, y, z = v

并解压缩到列表中?

[x, y, z] = v

2 个答案:

答案 0 :(得分:10)

绝对没有,甚至到字节码(使用dis):

>>> def list_assign(args):
    [x, y, z] = args
    return x, y, z

>>> def tuple_assign(args):
    x, y, z = args
    return x, y, z

>>> import dis
>>> dis.dis(list_assign)
  2           0 LOAD_FAST                0 (args) 
              3 UNPACK_SEQUENCE          3 
              6 STORE_FAST               1 (x) 
              9 STORE_FAST               2 (y) 
             12 STORE_FAST               3 (z) 

  3          15 LOAD_FAST                1 (x) 
             18 LOAD_FAST                2 (y) 
             21 LOAD_FAST                3 (z) 
             24 BUILD_TUPLE              3 
             27 RETURN_VALUE         
>>> dis.dis(tuple_assign)
  2           0 LOAD_FAST                0 (args) 
              3 UNPACK_SEQUENCE          3 
              6 STORE_FAST               1 (x) 
              9 STORE_FAST               2 (y) 
             12 STORE_FAST               3 (z) 

  3          15 LOAD_FAST                1 (x) 
             18 LOAD_FAST                2 (y) 
             21 LOAD_FAST                3 (z) 
             24 BUILD_TUPLE              3 
             27 RETURN_VALUE 

答案 1 :(得分:2)

没有。实际上x, y, z = v是以下的简写:

(x, y, z) = v

...正在元组中解压缩。发生了同样的行为:

>>> v = (1, 3, 4)
>>> [x, y, z] = v
>>> x, y, z
(1, 3, 4)
>>> x, y, z = v
>>> x, y, z
(1, 3, 4)