简体   繁体   中英

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.

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]) . Notice that other readings of 2014-09-28 remained the same. 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 pythonic solution will be duly appreciated.

Using if and else inside list comprehension .

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

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