我需要在列表中添加一个/多个元素,我有两个选择:
mylist=mylist+newlist
或(elemet)
或mylist.append(ele);
哪一个会更快?
答案 0 :(得分:1)
mylist.append(ele)
会更快。这在Python Docs中有记载。
从文档引用 -
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