![](/img/trans.png)
[英]What is the best way to create an object from each element in a python (numpy) array?
[英]what's the best way to subtract each element from the next element
我有很長的累積列表,我想從下一個元素中減去每個元素。 那么最好的方法是什么? “在可讀性和速度方面最好”
例如:清單為:
res = [0, 1, 4, 6, 7]
結果應為: output=[1, 3, 2, 1]
為了明確起見,輸出的最后一個元素來自output[-1]= res[-1] - res[-2]
因此,我嘗試了[xy for x, y in zip (res[::-1], res[::-1][1:])][::-1]
它是如此之快,但卻是復雜且難以理解的:“我想我將不記得接下來幾周的工作”
PS我正在使用res[::-1]
反轉列表
無需反轉; 只需將列表壓縮成對:
>>> [i - j for i, j in zip(res[1:], res[:-1])]
[1, 3, 2, 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.