vgndc vgndc - 11 months ago 37
Python Question

Python: Calculating difference of values in a nested list by using a While Loop

I have a list that is composed of nested lists, each nested list contains two values - a float value (file creation date), and a string (a name of the file).

For example:

n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]

The nested list is already sorted in order of ascending values (creation dates). I am trying to use a While loop to calculate the difference between each sequential float value.

For Example: 201609070753 - 201609070736 = 17

The goal is to use the time difference values as the basis for grouping the files.

The problem I am having is that when the count reaches the last value for
it throws an
is out of range.

IndexError: list index out of range

I can't figure out how to work around this error. no matter what i try the count is always of range when it reaches the last value in the list.

Here is the While loop I've been using.

count = 0

while count <= len(n_List):
full_path = source_folder + "/" + n_List[count][1]

time_dif = n_List[count+1][0] - n_List[count][0]

if time_dif < 100:
f_List.write(full_path + "\n")
count = count + 1
f_List.write(full_path + "\n")
f_List = open(source_folder + 'GoPro' + '_' + str(count) + '.txt', 'w')
f_List.write(full_path + "\n")
count = count + 1

PS. The only work around I can think of is to assume that the last value will always be appended to the final group of files. so, when the count reaches
len(n_List - 1)
, I skip the time dif calculation, and just automatically add that final value to the last group. While this will probably work most of the time, I can see edge cases where the final value in the list may need to go in a separate group.

Answer Source

I think using zip could be easier to get difference.

res1,res2 = [],[]
for i,j in zip(n_List,n_List[1:]):
    target = res1 if j[0]-i[0] < 100 else res2