Python赋值解构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24999875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python assignment destructuring
提问by sds
These three expressions seem to be equivalent:
这三个表达式似乎是等价的:
a,b,c = line.split()
(a,b,c) = line.split()
[a,b,c] = line.split()
Do they compile to the same code?
它们编译成相同的代码吗?
Which one is more pythonic?
哪个更pythonic?
采纳答案by dano
According to dis
, they all get compiled to the same bytecode:
根据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
So they should all have the same efficiency. As far as which is most Pythonic, it's somewhat down to opinion, but I would favor either the first or (to a lesser degree) the second option. Using the square brackets is confusing because it looks like you're creating a list (though it turns out you're not).
所以它们都应该具有相同的效率。至于哪个是最 Pythonic 的,这在某种程度上取决于意见,但我更喜欢第一个或(在较小程度上)第二个选项。使用方括号令人困惑,因为看起来您正在创建一个列表(尽管事实证明您不是)。