-1

我需要向列表中添加一个/多个元素,我有两个选项:

mylist=mylist+newlist或者(elemet)

或者mylist.append(ele);

哪个会更快?

4

1 回答 1

1

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
于 2013-08-04T09:14:02.637 回答