![](/img/trans.png)
[英]How to find the lowest difference between two numbers from the given list in python using nested while loop?
[英]Python: Calculating difference of values in a nested list by using a While Loop
我有一個由嵌套列表組成的列表,每個嵌套列表包含兩個值-浮點值(文件創建日期)和字符串(文件名)。
例如:
n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]
嵌套列表已經按照升序排列(創建日期)。 我正在嘗試使用While循環來計算每個順序浮點值之間的差異。
例如:201609070753-201609070736 = 17
目標是使用時差值作為對文件進行分組的基礎。
我遇到的問題是,當計數達到len(n_List)
的最后一個值時,它會引發IndexError
因為count+1
超出范圍。
IndexError: list index out of range
我不知道如何解決此錯誤。 無論我嘗試什么,當計數達到列表中的最后一個值時,計數始終在范圍內。
這是我一直在使用的While循環。
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
else:
f_List.write(full_path + "\n")
f_List.close()
f_List = open(source_folder + 'GoPro' + '_' + str(count) + '.txt', 'w')
f_List.write(full_path + "\n")
count = count + 1
PS。 我能想到的唯一解決方法是假設最后一個值將始終附加到最后一組文件中。 因此,當計數達到len(n_List - 1)
,我跳過了時間dif計算,只是將最終值自動添加到最后一組。 盡管這可能在大多數時間都有效,但我可以看到一些極少數情況,其中列表中的最終值可能需要放在單獨的組中。
n_list(len(n_list))將始終返回超出范圍的索引錯誤
while count < len(n_List):
應該足夠了,因為您從0開始計數,而不是1。
我認為使用zip可能會更容易獲得差異。
res1,res2 = [],[]
for i,j in zip(n_List,n_List[1:]):
target = res1 if j[0]-i[0] < 100 else res2
target.append(i[1])
僅供參考,這是我使用的解決方案,感謝@galaxyman的幫助。
我通過在循環完成后簡單地添加該值來處理嵌套列表中最后一個值的問題。 不知道這是否是最優雅的方法,但是它有效。
(注意:我只發布與先前文章中建議的zip方法相關的功能)。
def list_zip(get_gp_list):
ffmpeg_list = open(output_path + '\\' + gp_List[0][1][0:8] + '.txt', 'a')
for a,b in zip(gp_List,gp_List[1:]):
full_path = gopro_folder + '\\' + a[1]
time_dif = b[0]-a[0]
if time_dif < 100:
ffmpeg_list.write("file " + full_path + "\n")
else:
ffmpeg_list.write("file " + full_path + "\n")
ffmpeg_list.close()
ffmpeg_list = open(output_path + '\\' + b[1][0:8] + '.txt', 'a')
last_val = gp_List[-1][1]
ffmpeg_list.write("file " + gopro_folder + '\\' + last_val + "\n")
ffmpeg_list.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.