我想第二个很好:
>>> my_list = [1,2,3,4,5,6,7]
>>> length=len(my_list)
>>> index=2
>>> length-(index+1) #remaining elements are [4,5,6,7]
4
>>> index=4
>>> length-(index+1) #remaining elements are [6,7]
2
Timeit
结果,证明第二个比第一个切片更快:
import random
def func1():
lis=list(xrange(100))
for i in xrange(100):
index=random.randrange(0,100)
remainder = len(lis[index:])-1
def func2():
lis=list(xrange(100))
for i in xrange(100):
index=random.randrange(0,100)
remainder = (len(lis) - index) -1
if __name__ == '__main__':
from timeit import Timer
t = Timer("func2()", "from __main__ import func2")
print t.timeit()
t = Timer("func1()", "from __main__ import func1")
print t.timeit()
输出:
47.001240015
52.2959749699