這是我正在使用的檔案,名為 file1.txt
20
Gunsmoke
30
The Simpsons
10
Will & Grace
14
Dallas
20
Law & Order
12
Murder, She Wrote
到目前為止,這是我的代碼:
file = open('file1.txt')
lines = file.readlines()
print(lines)
new_list=[]
for i in lines:
new = i.strip()
new_list.append(new)
print(new_list)
new_dict = {}
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i 1]
if i in new_dict:
i[key] = i.values()
new_dict = dict(sorted(new_dict.items()))
print(new_dict)
file_2 = open('output_keys.txt', 'w')
for x, y in new_dict.items():
print(x, y)
file_2.write(x ': ')
file_2.write(y)
file_2.write('\n')
file_2.close()
file_3 = open('output_titles.txt', 'w')
new_list2 = []
for x, y in new_dict.items():
new_list2.append(y)
new_list2.sort()
print(new_list2)
print(new_list2)
for i in new_list2:
file_3.write(i)
file_3.write('\n')
print(i)
file_3.close()
指令狀態:
撰寫一個程式,首先讀取輸入檔案的名稱,然后使用該
file.readlines()方法讀取輸入檔案。輸入檔案包含一個未排序的季數串列,后跟相應的電視節目。您的程式應該將輸入檔案的內容放入字典中,其中季數是鍵,電視節目串列是值(因為多個節目可能具有相同的季數)。按鍵(從最小到最大)對字典進行排序,并將結果輸出到名為
output_keys.txt. 用分號 ( ) 分隔與同一鍵關聯的多個電視節目;,按輸入檔案中的出現順序排列。接下來,按值(字母順序)對字典進行排序,并將結果輸出到名為output_titles.txt.
所以我在兩個部分遇到問題的部分:
首先是“用分號 (;) 分隔與同一鍵關聯的多個電視節目”。
到目前為止,我所寫的只是替換了字典中的新條目。
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i 1]
if i in new_dict:
i[key] = i.values()
第二部分是在 Zybooks 程式中,它似乎在output_keys.txt每次output_title.txt迭代時都會添加。但是我的代碼似乎沒有添加到 output_keys 和 output_title 中。例如,如果在我運行之后我file1.txt嘗試運行file2.txt,它會替換output_keys而output_title不是添加到它。
uj5u.com熱心網友回復:
嘗試將問題分解為更小的子問題。現在,您似乎正試圖一次解決所有問題。例如,我建議您省略檔案輸入和輸出,而專注于程式的基本功能。設定好后,您可以進行 I/O。
您首先需要創建一個字典,其中季節數作為鍵,電視節目串列作為值。你幾乎明白了;這是一個作業片段(我重命名了您的一些變數:使用有意義的變數名總是一個好主意):
lines = file.readlines()
# formerly "new_list"
clean_lines = []
for line in lines:
line = line.strip()
clean_lines.append(line)
# formerly "new_dict"
seasons = {}
for i in range(0, len(clean_lines), 2):
season_num = int(clean_lines[i])
series = clean_lines[i 1]
# there are only two options: either
# the season_num is already in the dict...
if season_num in seasons:
# append to the existing entry
seasons[season_num].append(series)
# ...or it isn't
else:
# make a new entry with a list containing
# the series
seasons[season_num] = [series]
以下是如何列印結果字典,其中電視節目用分號分隔,使用join. 適應您的需求:
for season_num, series in seasons.items():
print(season_num, '; '.join(series))
輸出:
20 Gunsmoke; Law & Order
30 The Simpsons
10 Will & Grace
14 Dallas
12 Murder, She Wrote
uj5u.com熱心網友回復:
如我所見,您嘗試檢查該鍵是否已存在于字典中,但那里似乎有錯誤,您應該檢查該值而不是索引是否存在于字典中,并且您必須在放入字典之前檢查它是否存在退出您可以通過添加來更新當前值;結束當前值
for i in range(0,len(new_list),2):
if not new_list[i] in new_edict.keys():
new_edict[new_list[i]] = new_list[i 1]
else:
Update it here… like
new_list[new_list[i]] = new_list[new_list[i]] ";" new_list[i 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463543.html
上一篇:淺談前端性能優化
