简体   繁体   中英

Finding the running difference between elements in the same index of different sublists within a nested list

I have a nested list, through which I must iterate and compare (and subsequently operate with) elements in the same position/index of each sublist. For example, here is a minimum reproducible program:

a = [[1,2,3], [1,4,7], [2,0,8], [5,1,1]] #nested list

b = [[1,2,3], [0,2,4], [1,-4,1], [3,1,-7]] #desired output

I need to essentially create a new nested list, where each subsequent sublist in the solution is the difference between the sublist in the same position/index in the original nested list and the sublist in the position/index before in the original nested list. ie, the first sublist in b is just the first sublist in a, the second sublist in b is the second sublist in a subtract the first sublist in a, the third sublist in b is the third sublist in a subtract the second sublist in a, ...., and the nth sublist in b is the nth sublist in a subtract the nth-1 sublist in a.

I need to do this in an automative and iterative manner since these lists I've provided above are not the real lists - the real nested lists contain thousands of sublists. I am new to python so if this is very simple I apologise - if this is the case, if you could direct me to a solution I would very much appreciate it.

np.diff is designed for it:

import numpy as np
b = np.r_[[a[0]], np.diff(a, axis=0)]

Note that output is numpy array. It works much faster than standard Python iterations.

import numpy as np

a = [[1,2,3], [1,4,7], [2,0,8], [5,1,1]] 
b = [a[0], *[list(i) for i in np.diff(a, axis=0)]]

Alternatively, if you want to use pure Numpy methods then

b = np.ndarray.tolist(np.r_[[a[0]], np.diff(a, axis=0)])

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