我收到了一個包含 500 部電影的文本檔案,格式如下:“名稱”\t“總收入”
我必須撰寫一個按總收入對電影進行排序的函式,然后將排序后的內容寫入目標檔案。
我被困在多個計數上,出現的錯誤訊息是這樣的:
split[1]= int(split[1]) IndexError: list index out of range Command exited with non-zero status 1
import re
def sort_films(source, destination):
source= open(source)
destination = open(destination, "w")
full_list=[]
for line in source:
split= re.split("\t|\n", line)
split.pop()
split[1]= int(split[1])
full_list.append(split)
full_list.sort(key= lambda i:i[1], reverse=True)
print(full_list, file=destination)
source.close()
destination.close()
sort_films("top500.txt", "top500result.txt")
print("Done!")
uj5u.com熱心網友回復:
您正在洗掉 2 元素串列的第一個元素,然后嘗試訪問現在 1 元素串列的第二個元素。洗掉split.pop()或替換索引in split[1] = int(split[1])。0
uj5u.com熱心網友回復:
shell 可以輕松做到這一點
cat top500.txt |sort -n -k 2 > top500result.txt
uj5u.com熱心網友回復:
如果檔案中只有兩列,則在讀取一行時會得到一個 2 元素串列。由于“split”在每次迭代中都是一個 2 元素串列,因此 pop() 將洗掉最后一個元素,導致串列最后只有 1 個元素。用 1 索引“拆分”串列將是無效的,因為“拆分”現在是一個 1 元素串列,python 從 0 開始索引串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410646.html
標籤:
