简体   繁体   English

Python嵌套列表获取特定索引的连续值之差

[英]Python nested list get difference of consecutive values of a particular index

I have a nested list of each day and its values in following format: 我有以下格式的每天嵌套列表及其值:

a_list = [[datetime,value,counter_value],[datetime,value,counter_value]]

that is: 那是:

a_list = [['2014-09-27', 2,4],['2014-09-28', 3, 7],['2014-09-29',5,9],['2014-09-30',2,14], ['2014-10-01',2,4]]

Notice that the 2nd index value of each nested list is gradually increasing and is basically like a counter value which resets . 请注意,每个嵌套列表的第二个索引值都在逐渐增加,并且基本上像一个重置的计数器值。 I wanted to know a pythonic way of subtracting only 2nd indexes of consecutive lists so as to get the count difference of each interval. 我想知道一种仅减去连续列表的第二个索引的Python方法,以便获得每个间隔的计数差。

Like if I wanted to know how much difference of count is on 2014-09-28, I will subtract count value of 2014-09-27 from 2014-09-28 ie 7 - 4 = 3 and my resultant reading will be ['2014-09-28', 3, 3 ] (instead of ['2014-09-28', 3, 7]) . 就像我想知道2014-09-28的计数差异有多少一样,我将从2014-09-28减去2014-09-27的计数值,即7-4 = 3,我得到的读数将是[' 2014年9月28'日,3,3](而不是[ '2014年9月28日',3,7])。 Notice that other readings of 2014-09-28 remained the same. 请注意,2014-09-28的其他读数保持不变。 So in this manner, the final list will be: 因此,以这种方式,最终列表将是:

b_list = [['2014-09-28', 3, **3**],['2014-09-29',5,**2**],['2014-09-30',2,**5**], ['2014-10-01',2,**4**]]

and if the current counter value is less than the previous one, this means the counter has been reset and keep the current value without subtraction like in the last value of a_list. 如果当前计数器的值小于前一个值,则表示该计数器已被重置,并且保持当前值不减,就像a_list的最后一个值一样。 A pythonic solution will be duly appreciated. pythonic解决方案将不胜感激。

Using if and else inside list comprehension . list comprehension使用ifelse

>>> a_list
[['2014-09-27', 2, 4], ['2014-09-28', 3, 7], ['2014-09-29', 5, 9], ['2014-09-30', 2, 14], ['2014-10-01', 2, 4]]
>>> [ a_list[i][:-1] + [a_list[i][2]-a_list[i-1][2]] if a_list[i][2]-a_list[i-1][2] > 0 else a_list[i] for i in range(1,len(a_list)) ]
[['2014-09-28', 3, 3], ['2014-09-29', 5, 2], ['2014-09-30', 2, 5], ['2014-10-01', 2, 4]]

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

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