50

这三个表达式似乎是等价的:

a,b,c = line.split()
(a,b,c) = line.split()
[a,b,c] = line.split()

它们编译成相同的代码吗?

哪个更pythonic?

4

1 回答 1

63

根据dis,它们都被编译为相同的字节码:

>>> def f1(line):
...  a,b,c = line.split()
... 
>>> def f2(line):
...  (a,b,c) = line.split()
... 
>>> def f3(line):
...  [a,b,c] = line.split()
... 
>>> import dis
>>> dis.dis(f1)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> dis.dis(f2)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> dis.dis(f3)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        

所以他们都应该有同样的效率。至于哪个是最 Pythonic 的,这在某种程度上取决于意见,但我会赞成第一个或(在较小程度上)第二个选项。使用方括号会让人感到困惑,因为它看起来像是在创建一个列表(尽管事实证明你不是)。

于 2014-07-28T16:38:09.163 回答