简体   繁体   English

如何互相减去numpy数组中的相邻向量

[英]How to subtract neighbouring vectors in a numpy array from each other

My expected results are as follows: 我的预期结果如下:

array = [[2,3,4], [1,2,4]]

Output: 输出:

[1, 1, 0]  # [2-1, 3-2, 4-4]

I tried doing this by enumerating and getting the indexes to subtract with no luck as: 我尝试通过枚举并让索引减去没有运气的方式来这样做:

for i, k in enumerate(array):
    for j in k:
        return(j[i+1] - j[i])

Which gives me: 这给了我:

IndexError: invalid index to scalar variable. IndexError:标量变量的索引无效。

This works: 这有效:

result = [(i-j) for (i,j) in zip(*array)]

Output: 输出:

print (result)
[1, 1, 0]

Explanation: 说明:

zip(*array) is equivalent to the list of tuples [(2,1), (3,2), (4,4)] zip(*array)等效于元组列表[(2,1), (3,2), (4,4)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM