我不斷收到錯誤訊息,提示我的索引值超出范圍。這是我正在使用的文本檔案:
The Lion King (2019): 6.0
The Lion King (2019): 7.5
The Lion King (2019): 5.1
Titanic (1997): 7
代碼:
#function that will return the dictionary
def read_ratings_data(f):
#to store the lines read from the file
lines = []
#defining the dictionary
movie_ratings_dict = {}
#open read file
#read lines and store
#closes file
with open (f, "r") as file:
lines = file.readlines()
file.close()
#should remove \n symbol
#converts text into list of movie rating
#ISSUE: keep getting an error with the third line not sure how to fix
for i in range(len(lines)):
temp = lines[i][: -1].split(".")
lines[i] = [temp[0], float(temp[1])]
#stores data into dict
for i in lines:
#if statement when there is a new movie in the text
#will create a new list for that movie (key)
if i[0] not in movie_ratings_dict:
movie_ratings_dict[i[0]] = []
#appends the rating as in, as we encounter new ratings, will add to the end
movie_ratings_dict[i[0]].append(i[1])
#return dict ending
return movie_ratings_dict
read_ratings_data("movie_ratings.txt")
uj5u.com熱心網友回復:
你已經使這比它需要的復雜得多。
輸入檔案的電影標題似乎以“:”結尾。因此,我們需要任何一方的令牌 - 即標題和評級。
目標是創建一個以電影名稱為鍵的字典,其值是所有已知評級的串列。
因此,打開檔案并一次讀取一行,將每一行分成兩個組成部分。
在串列中使用 setdefault。如果給 setdefault(鍵)的第一個引數不存在,則將回傳默認值(在本例中為空串列)并與字典中的該鍵相關聯。
即使第二個標記(評級)將換行符作為其最后一個字符,我們也可以利用float()不受空格影響的事實。因此,例如,float('1.5\n')將回傳 1.5
def read_ratings_data(filename):
result = {}
with open(filename) as file:
for line in file:
title, rating = line.split(':')
result.setdefault(title, []).append(float(rating))
return result
print(read_ratings_data('ratings.txt'))
輸出:
{'The Lion King (2019)': [6.0, 7.5, 5.1], 'Titanic (1997)': [7.0]}
uj5u.com熱心網友回復:
當您使用分隔符“。”拆分“泰坦尼克號(1997):7”時,您將面臨錯誤,由于沒有“。”,因此不會創建元素串列。特點。因此獲取 temp[1] 的錯誤檢查 temp 變數的 len(),然后根據要求分配它。
在 Python 中,“for i in lines”與 C/C 中的不同。這里變數“i”將根據每次迭代存盤完整的字串。
if i[0] not in movie_ratings_dict: 可以替換為 if i not in movie_ratings_dict: 在其他地方類似。
uj5u.com熱心網友回復:
您應該根據:分隔符進行拆分。
只需更改這部分代碼,它就可以正常作業。
for i in range(len(lines)):
temp = lines[i].split(":")
lines[i] = [temp[0], float(temp[1])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434460.html
上一篇:是否有映射迭代器的每個元素的函式。下一個對應的另一個?
下一篇:根據嵌套串列中元素的位置創建字典
