列表中连续元素之间的差异 [英] Difference between consecutive elements in list
本文介绍了列表中连续元素之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Python-列表元素之间的差异
Possible Duplicate:
Python - Differences between elements of a list
我有一个列表,我想找到连续元素之间的区别:
I have a list and I want to find difference between consecutive elements:
a = [0, 4, 10, 100]
find_diff(a)
>>> [4,6,90]
您如何编码find_diff()函数?我可以使用"for"迭代器对此进行编码,但是我敢肯定,有一种非常简单的方法可以使用一个简单的内衬来实现它.
How would you code find_diff() function? I can code this with "for" iterator but I am sure there are very simple ways to do it with a simple one liner.
推荐答案
>>> a = [0, 4, 10, 100]
# basic enumerate without condition:
>>> [x - a[i - 1] for i, x in enumerate(a)][1:]
[4, 6, 90]
# enumerate with conditional inside the list comprehension:
>>> [x - a[i - 1] for i, x in enumerate(a) if i > 0]
[4, 6, 90]
# the zip version seems more concise and elegant:
>>> [t - s for s, t in zip(a, a[1:])]
[4, 6, 90]
在性能方面,似乎没有太多差异:
Performance-wise, there seems to be not too much variance:
In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:]
1000000 loops, best of 3: 1.34 µs per loop
In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0]
1000000 loops, best of 3: 1.11 µs per loop
In [7]: %timeit [t - s for s, t in zip(a, a[1:])]
1000000 loops, best of 3: 1.1 µs per loop
这篇关于列表中连续元素之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文