給正在閱讀本文的人。我在完成第一門 Python 課程的作業時遇到問題。我需要做的是我需要創建一個程式,該程式讀取一個包含不同歌曲、它們的流派和它們的評級的檔案。這些資訊將在一個檔案中,每堆資訊一行。像這樣:
Rap;Gangsta's paradise;88
Pop;7 rings;90
Classic;La Campanella;72
Rap;Still D.R.E;82
Pop;MONTERO;79
在程式中,我只能選擇一個好的資料結構(它是兩個更簡單的資料結構的組合),檔案中的資料將保存在其中。通過使用我正在創建的資料結構,我有望完成不同型別的功能,例如列印出所有內容并在其中添加新內容等。
我選擇通過組合 dict 和 list 來制作資料結構,就像創建一個 dict,其中鍵是流派,其值是 [歌曲及其評分] 的串列。(我不確定這是否是最明智的方法......)
但是,我現在無法開始我的代碼,因為我無法正確創建資料結構。正如我所嘗試的那樣,我只導致了一些情況,在這種情況下,我可以獲得正確的字典鍵值(流派),但是作為字典值的串列給我帶來了麻煩。
這是我的代碼:
def main():
filename = input("Please, enter the file name: ")
# Opening the file in try-except bracket. If the file can't be opened, the
# program prints out an error message and shuts down.
try:
file = open(filename, mode="r")
except OSError:
print("Error opening the selected file!")
return
# Defining a dict, where the lists will be inputed.
dict = {}
# Going trough each line in the file.
for line in file:
# Breaking each line of the file into a list.
line = line.strip()
parts = line.split(";")
# Defining variables for different list values. The values will
# be in the file in this order.
genre = parts[0]
track = parts[1]
rating = int(parts[2])
# Inputing each every data in the dict like this:
# genre is the dict's key and track, rating are the values IN A LIST!
if genre not in dict:
dict[genre] = []
dict[genre].append(track)
dict[genre].append(rating)
# The dict now looks like this:
# {'Rap': ["Gangsta's paradise", 88, 'Still D.R.E', 82], etc.
# When it should look like this:
# {'Rap': [["Gangsta's paradise", 88], ['Still D.R.E', 82]], etc.
# Wrong type values now cause problems in this print section, because
# I can't print out all possible songs in a specific rating, because I
# can't go trough the lists properly.
for genres in dict:
print(genres.upper())
print(f"{dict[genres][0]}, rating: {dict[genres][1]}/100")
file.close()
if __name__ == "__main__":
main()
最后我想說,在你嘗試通過格式化我的代碼來幫助我之前:這是最好的方法,還是有更簡單的資料結構,可以幫助我完成我的任務?非常感謝您,這對我來說意義重大。
uj5u.com熱心網友回復:
這顯示了將曲目和評分一起存盤在一個元組中,以及如何遍歷您收集的元組:
def main():
filename = input("Please, enter the file name: ")
# Opening the file in try-except bracket. If the file can't be opened, the
# program prints out an error message and shuts down.
try:
file = open(filename, mode="r")
except OSError:
print("Error opening the selected file!")
return
# Defining a data, where the lists will be inputed.
data = {}
# Going trough each line in the file.
for line in file:
# Breaking each line of the file into a list.
line = line.strip()
parts = line.split(";")
# Defining variables for different list values. The values will
# be in the file in this order.
genre = parts[0]
track = parts[1]
rating = int(parts[2])
if genre not in data:
data[genre] = []
data[genre].append((track,rating))
for genre,tunes in data.items():
print(genre.upper())
for tune in tunes:
print(f"{tune[0]}, rating: {tune[1]}/100")
file.close()
if __name__ == "__main__":
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365720.html
