Reputation: 15
I want to compare the first element from a sublist (Index [0]) to the same element from the sublist right before it. if it's not equal, I want to append a new element to the sublist that would be 0. if they are equal, i want to append the result of the sum of two second elements (ex: 12+12 = 24)
I dont know how to reference the data from the sublist before the one I examine in my loop to achieve the comparison because I just get some 0 appended.I'm pretty sure it's the way I did my referencing of the previous index that is wrong.
list = [['1046', '10'], ['1047','12'], ['1047','12']]
for sublists in list:
if sublists[1] != sublists[1 - 1]:
sublists.append(0)
else:
velocity = float(sublists[2]) + float(sublists[2 - 1])
sublists.append(velocity)
and the resulting list is :
R_list = [['1046', '10', 0], ['1047', '12', 0], ['1047', '12', 0]]
While I wanted:
R_list = [['1046', '10', 0], ['1047', '12', 0], ['1047', '12', 24]]
Upvotes: 1
Views: 291
Reputation: 10624
Your indexing is not correct in general. Try something like the following:
for i in range(1,len(R_list)):
if R_list[i][0]!=R_list[i-1][0]:
R_list[i].append(0)
else:
R_list[i].append(int(R_list[i][1])+int(R_list[i-1][1]))
For
R_list = [['1046', '10', 0], ['1047', '12', 0], ['1047', '12', 0]]
the above gives:
[['1046', '10', 0], ['1047', '12', 0, 0], ['1047', '12', 0, 24]]
Upvotes: 1