我需要向列表中添加一个/多个元素,我有两个选项:
mylist=mylist+newlist
或者(elemet)
或者mylist.append(ele);
哪个会更快?
我需要向列表中添加一个/多个元素,我有两个选项:
mylist=mylist+newlist
或者(elemet)
或者mylist.append(ele);
哪个会更快?
mylist.append(ele)
会更快。这记录在 Python 文档中。
引用文档 -
The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient.
myList = myList + something
必须创建一个新列表并重新分配它。
比较timeit
结果 -
>>> timeit('myList = myList + ["a"]', 'myList = []', number = 50000)
11.35058911138415
>>> timeit('myList.append("a")', 'myList = []', number = 50000)
0.010776052286637139