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

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

它们是否编译为相同的代码?

哪一个更适合pythonic?

最佳答案

根据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

因此,它们都应具有相同的效率。至于哪个是最Python化的,这有点可取,但是我倾向于第一种选择(或在较小程度上)第二种选择。使用方括号会造成混淆,因为看起来您正在创建列表(尽管事实并非如此)。

关于python - Python作业分解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24999875/

10-09 20:57