简体   繁体   English

查找嵌套列表中不同子列表的相同索引中的元素之间的运行差异

[英]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.即,b中的第一个子列表只是a中的第一个子列表,b中的第二个子列表是a中的第二个子列表减去a中的第一个子列表,b中的第三个子列表是a中的第三个子列表减去a中的第二个子列表, ...., b中的第n个子列表是a中的第n个子列表减去a中的第n-1个子列表。

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.我是 python 的新手,所以如果这很简单,我深表歉意 - 如果是这种情况,如果您能指导我找到解决方案,我将非常感激。

np.diff is designed for it: np.diff是为它设计的:

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

Note that output is numpy array.请注意,output 是numpy数组。 It works much faster than standard Python iterations.它比标准的 Python 迭代快得多。

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或者,如果您想使用纯 Numpy 方法,则

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

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

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