Python作业解构 [英] Python assignment destructuring
本文介绍了Python作业解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这三个表达式似乎是等效的:
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?
哪个是更pythonic的?
Which one is more pythonic?
推荐答案
根据 dis
,它们都被编译为相同的字节码:
According to dis
, they all get compiled to the same bytecode:
>>> 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化的,这有点可取,但是我会选择第一个选项(或在较小程度上)选择第二个选项.使用方括号会造成混淆,因为看起来您正在创建列表(尽管事实并非如此).
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).
这篇关于Python作业解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文