在Python中创建一个空列表 [英] Creating an empty list in Python
本文介绍了在Python中创建一个空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中创建新的空列表的最佳方法是什么?
What is the best way to create a new empty list in Python?
l = []
或
l = list()
我问这是因为两个原因:
I am asking this because of two reasons:
- 技术原因,其中更快。 (创建类会导致开销?)
- 代码可读性 - 这是标准惯例。
推荐答案
这里是如何测试哪个代码更快:
Here is how you can test which piece of code is faster:
% python -mtimeit "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop
% python -mtimeit "l=list()"
1000000 loops, best of 3: 0.297 usec per loop
可能是你的程序的一小部分,所以担心这可能是错误的。
However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.
可读性是非常主观的。我喜欢 []
,但一些非常有见识的人,比如Alex Martelli,更喜欢 list()
,因为可以发音。
Readability is very subjective. I prefer []
, but some very knowledgable people, like Alex Martelli, prefer list()
because it is pronounceable.
这篇关于在Python中创建一个空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文