在Python 3中,使用
list()
和[]
初始化一个list
是否有区别?由于list()
是一个返回列表对象的函数,而[]
则是列表对象本身。第二种形式更快,因为它不涉及函数调用:
> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop
> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop
它们几乎是等价的;构造函数变体执行函数查找和函数调用;而文字常量则不执行-反汇编Python字节码显示:
from dis import dis
def list_constructor():
return list()
def list_literal():
return []
print("constructor:")
dis(list_constructor)
print()
print("literal:")
dis(list_literal)
constructor:
5 0 LOAD_GLOBAL 0 (list)
2 CALL_FUNCTION 0
4 RETURN_VALUE
literal:
8 0 BUILD_LIST 0
2 RETURN_VALUE
$ python3 -m timeit 'list(range(7))'
1000000 loops, best of 5: 224 nsec per loop
$ python3 -m timeit '[i for i in range(7)]'
1000000 loops, best of 5: 352 nsec per loop
使用 list
从生成器构建列表比使用列表推导式更快。我认为这是因为列表推导式中的 for
循环是 Python 循环,而在 Python 解释器中的 C
实现中,相同的循环在 list
版本中运行。
同时请注意,list
可以被重新赋值为其他变量(例如,list = int
,现在 list()
将返回整数 0
),但你不能修改 []
。
并且,虽然可能很显然,但为了完整起见:这两个版本具有不同的接口:list
接受一个可迭代对象作为参数。它将遍历它,并将元素放入新的列表中;字面量版本则不会(除了显式的列表推导式):
print([0, 1, 2]) # [0, 1, 2]
# print(list(0, 1,2)) # TypeError: list expected at most 1 argument, got 3
tpl = (0, 1, 2)
print([tpl]) # [(0, 1, 2)]
print(list(tpl)) # [0, 1, 2]
print([range(3)]) # [range(0, 3)]
print(list(range(3))) # [0, 1, 2]
# list-comprehension
print([i for i in range(3)]) # [0, 1, 2]
print(list(i for i in range(3))) # [0, 1, 2] simpler: list(range(3))
这两种方式在功能上产生相同的结果,但是Python内部实现不同:
import dis
def brackets():
return []
def list_builtin():
return list()
print(dis.dis(brackets))
5 0 BUILD_LIST 0
2 RETURN_VALUE
print(dis.dis(list_builtin))
9 0 LOAD_GLOBAL 0 (list)
2 CALL_FUNCTION 0
4 RETURN_VALUE
让我们来看一个例子:
A = ("a","b","c")
B = list(A)
C = [A]
print("B=",B)
print("C=",C)
# list is mutable:
B.append("d")
C.append("d")
## New result
print("B=",B)
print("C=",C)
Result:
B= ['a', 'b', 'c']
C= [('a', 'b', 'c')]
B= ['a', 'b', 'c', 'd']
C= [('a', 'b', 'c'), 'd']
list() 方法接受序列类型并将它们转换为列表。这用于将给定的元组转换为列表。
sample_touple = ('a', 'C', 'J', 13)
list1 = list(sample_touple)
print ("List values ", list1)
string_value="sampletest"
list2 = list(string_value)
print ("List string values : ", list2)
输出:
List values ['a', 'C', 'J', 13]
List string values : ['s', 'a', 'm', 'p', 'l', 'e', 't', 'e', 's', 't']
在编程中,如何使用[]
直接声明为列表
sample = [1,2,3]
int(0)
和0
。实际上它们之间没有区别。 - jfaccioni[]
会更快,因为它不需要全局查找再调用函数。除此之外,它与原来的内容一样。 - bereal