简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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