差异

2011-03-15 27 views
18

可能重复:
Python - Differences between elements of a list差异

我有一个名单,我想找到连续元素之间的区别:

a = [0, 4, 10, 100] 
find_diff(a) 
>>> [4,6,90] 

将如何你的代码find_diff()函数?我可以用“for”迭代器编写这个代码,但我确信有一个简单的方法可以用一个简单的一行代码来完成。

+0

嗯,我会接受的第一个答案,但我看它现在删除。 – gok 2011-03-15 15:57:30

+0

本来应该是这样的,因为这个问题**要求完全一样**。 – 2011-03-15 15:58:24

+0

所以我应该删除这个问题?在询问之前我无法在搜索中找到那一个 – gok 2011-03-15 15:59:26

回答

28

你可以利用enumerateziplist comprehensions

>>> 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] 

性能的角度来看,似乎是没有太多的差异:

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 
16

使用recipe for pairwise从迭代工具文档:

from itertools import izip, tee 
def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    return izip(a, b) 

使用它是这样的:

>>> a = [0, 4, 10, 100] 
>>> [y-x for x,y in pairwise(a)] 
[4, 6, 90] 
+1

这完全没有必要。参见[Python - 列表元素之间的差异](http://stackoverflow.com/questions/2400840/python-differences-between-elements-of-a-list)。 – 2011-03-15 15:59:04

+12

@Matt Ball:许多迭代器可以被称为“不必要的”,但是一旦定义,它们就会对常见的习惯用法有用。为什么要求读者在拼写一个有用的名字时,拼出两个切片的zip文件,如'pairwise'。我不认为我一个人在思考这个问题,因为我直接从文档中解除了这个例子。 – 2011-03-15 16:13:22

+0

+!此版本适用于任意发生器,不能被分割/索引。 – avmohan 2017-09-04 15:55:42

3
[x - a[i-1] if i else None for i, x in enumerate(a)][1:]