如何从这个输出中减去或找到差异?

How to subtract or find the differences from this output?

这里是新手,刚刚进入 Python 一周。 所以我想做的是找出如何从我得到的输出中找出差异。 假设我有 [ 5 8 10 8 11] 现在我想要 8-5、10-8、8-10、11-8。 我该如何实现?赐教。

import numpy as np
import random
ll = list(range(5))

a = np.array(range(5))

b = np.array(random.choices(ll, k=5))

c = np.array([5])

print(a+b+c)

您可以使用列表理解来尝试这种方式:

>>> out = [7, 7, 10, 9, 12]  # a normal python list
>>> out_diff = [ (i-j) for j, i in zip(out[:-1], out[1:]) ]
>>> out_diff
[0, 3, -1, 3]

而且由于您使用的是 numpy,因此更简单:

>>> out[:-1] - out[1:]  # without using functions
array([ 0, -3,  1, -3])

或使用np.diff:

>>> np.diff(out)  # assumed 'out' is a numpy array instance
array([ 0,  3, -1,  3])

实现它的简单方法

lst=[5,8,10,8,11]
new_lst=[]
for i in range(1,len(lst)):
    new_lst.append(lst[i]-lst[i-1])

我认为您正在寻找 Numpy 模块中的函数“ediff1d”。有关详细信息,请访问此 link:numpy.ediff1d documentation

查看示例代码:

import numpy as np

array = [5, 8, 10, 8, 11]
print(array)
print(np.ediff1d(array))

输出:

[5, 8, 10, 8, 11]
[ 3  2 -2  3]