[英]what's the best way to subtract each element from the next element
I have very long accumulated list, and i want to subtract each element from the next element. 我有很长的累积列表,我想从下一个元素中减去每个元素。 So what's the best way? 那么最好的方法是什么? "The best in terms of readability and speed " “在可读性和速度方面最好”
Ex: the list is: 例如:清单为:
res = [0, 1, 4, 6, 7]
And the result should be : output=[1, 3, 2, 1]
结果应为: output=[1, 3, 2, 1]
To clarify, the last element of the output came from output[-1]= res[-1] - res[-2]
为了明确起见,输出的最后一个元素来自output[-1]= res[-1] - res[-2]
So I've tried [xy for x, y in zip (res[::-1], res[::-1][1:])][::-1]
因此,我尝试了[xy for x, y in zip (res[::-1], res[::-1][1:])][::-1]
It's so fast, but it's complicated and not readable "I think i will not remember what i did in the next couple of weeks" 它是如此之快,但却是复杂且难以理解的:“我想我将不记得接下来几周的工作”
PS I am reversing the list using res[::-1]
PS我正在使用res[::-1]
反转列表
No need to reverse; 无需反转; just zip the list up into pairs: 只需将列表压缩成对:
>>> [i - j for i, j in zip(res[1:], res[:-1])]
[1, 3, 2, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.