由於沒有lambda表達式:
[l[i+1] - l[i] for i in range(len(l) - 1)]
如:
>>> l = [1, 4, 8, 15, 16]
>>> [l[i+1] - l[i] for i in range(len(l) - 1)]
[3, 4, 7, 1]
更快一點,因爲你可以看到(編輯:添加最投票解決方案https://stackoverflow.com/a/2400875/1171280):
>>> import timeit
>>>
>>> s = """\
... l = [1, 4, 7, 15, 16]
... [l[i+1] - l[i] for i in range(len(l) - 1)]
... """
>>> r = """\
... l = [1, 4, 7, 15, 16]
... [j - i for i,j in zip(l[:-1], l[1:])]
... """
>>> t = """\
... l = [1, 4, 7, 15, 16]
... [j-i for i, j in itertools.izip(l[:-1], l[1:])]
... """
>>> timeit.timeit(stmt=s, number=100000)
0.09615588188171387
>>> timeit.timeit(stmt=s, number=100000)
0.09774398803710938
>>> timeit.timeit(stmt=s, number=100000)
0.09683513641357422
#-------------
>>> timeit.timeit(stmt=r, number=100000)
0.14137601852416992
>>> timeit.timeit(stmt=r, number=100000)
0.12511301040649414
>>> timeit.timeit(stmt=r, number=100000)
0.12285017967224121
#-------------
>>> timeit.timeit(stmt=t, number=100000)
0.11506795883178711
>>> timeit.timeit(stmt=t, number=100000)
0.11677718162536621
>>> timeit.timeit(stmt=t, number=100000)
0.11829996109008789
您應該發佈這兩種解決方案,他們會比較容易比較。 – TheSoundDefense
如果您不想構建列表副本,請使用'itertools.izip'和'itertools.islice'。 – jonrsharpe
@TheSoundDefense:的確,謝謝。我編輯了我的帖子。 – Jokyjo