简体   繁体   English

删除列表最后一个元素的最有效方法是什么?

[英]Most efficient way to remove last element of list?

With the list: [-1, 0, 43, 128, 32] , there are a couple ways of removing the final element. 使用列表: [-1, 0, 43, 128, 32] ,有几种方法可以删除最终元素。

  • list.pop()
  • list = list[:-1] (not recommended?) list = list[:-1] (不推荐?)
  • del list[-1]
  • And probably a couple more... 可能还有几个......

They would all return [-1, 0, 43, 128] , but what's least computationally intensive and does it make a difference? 他们都会返回[-1, 0, 43, 128] ,但是计算密集程度最低,是否会产生影响? I'm aware of modules like timeit which I could use to test this for myself. 我知道像timeit这样的模块,我可以用来为自己测试这个。 But I'm wary of uncontrolled variables and my non-expertise could definitely dilute the results. 但我对不受控制的变量持谨慎态度,而我的非专业知识肯定会削弱结果。 As well, does the best option differ for strings, or floats, or booleans? 同样,字符串,浮点数或布尔值的最佳选择是否不同? What about multidimensional lists? 多维列表怎么样?

I'm not quite sure how to control and test these variables, so I'd figure I'd ask here to see if there is a general hierarchy. 我不太确定如何控制和测试这些变量,所以我想我会在这里询问是否存在一般层次结构。

Not a Duplicate of Difference between del, remove and pop on lists del,删除和弹出列表之间差异不重复

That question explains the differences between methods of deletion, but does not address slicing. 该问题解释了删除方法之间的差异,但没有解决切片问题。 It also does not address speed at all. 它根本没有解决速度问题。 The accepted answer makes vague mentions to efficiency which I can see being part of the solution, but I do not see how it fits with slicing. 接受的答案对效率提出了模糊的提及,我可以看到它是解决方案的一部分,但我不知道它如何适合切片。

As per mentioned in the Python wiki . 正如Python wiki中提到的那样。 Time complexities are as follows: 时间复杂性如下:

  • Pop last O(1) Pop last O(1)
  • Delete Item O(n) 删除项目O(n)
  • Set Slice O(k+n) 设置切片O(k+n)

Experimental Study 实验研究

import time

all_t = 0.
for i in range(1000):
    list_ = [i for i in range(100000)]
    start_ = time.time()
    list_.pop()
    all_t += time.time() - start_
print("Average Time for POP is {}".format(all_t/1000.))

all_t = 0.
for i in range(1000):
    list_ = [i for i in range(100000)]
    start_ = time.time()
    del list_[-1]
    all_t += time.time() - start_
print("Average Time for DEL is {}".format(all_t/1000.))

all_t = 0.
for i in range(1000):
    list_ = [i for i in range(100000)]
    start_ = time.time()
    list_ = list_[:-1]
    all_t += time.time() - start_
print("Average Time for SLICE is {}".format(all_t/1000.))

Results 结果

Average Time for POP is 7.793903350830078e-07
Average Time for DEL is 9.80854034423828e-07
Average Time for SLICE is 0.0006206443309783935

Summary 摘要

pop() is the fastest when you do not specify an index. 如果不指定索引, pop()是最快的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM