list() 和 [] 有什么区别 [英] What's the difference between list() and []
本文介绍了list() 和 [] 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码有什么区别:
foo = list()
和
foo = []
Python 表明有一种做事方式,但有时似乎不止一种.
解决方案
一个是函数调用,一个是字面量:
<预><代码>>>>导入文件>>>def f1(): 返回列表()...>>>def f2(): 返回 []...>>>dis.dis(f1)1 0 LOAD_GLOBAL 0(列表)3 CALL_FUNCTION 06 RETURN_VALUE>>>dis.dis(f2)1 0 BUILD_LIST 03 RETURN_VALUE使用第二种形式.它更 Pythonic,而且可能更快(因为它不涉及加载和调用单独的函数).
What's the difference between the following code:
foo = list()
And
foo = []
Python suggests that there is one way of doing things but at times there seems to be more than one.
解决方案
One's a function call, and one's a literal:
>>> import dis
>>> def f1(): return list()
...
>>> def f2(): return []
...
>>> dis.dis(f1)
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>> dis.dis(f2)
1 0 BUILD_LIST 0
3 RETURN_VALUE
Use the second form. It's more Pythonic, and it's probably faster (since it doesn't involve loading and calling a separate funciton).
这篇关于list() 和 [] 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文