【发布时间】:2021-07-31 11:02:55
【问题描述】:
我必须编写一个程序,首先读取输入文件的名称,然后使用 file.readlines() 方法读取输入文件。输入文件包含一个未排序的季数列表,后跟相应的电视节目。程序将输入文件的内容放入字典中,其中季数是键,电视节目列表是值(因为多个节目可能具有相同的季数)。按键(从最小到最大)对字典进行排序,并将结果输出到名为 output_keys.txt 的文件中,用分号 (;) 分隔与同一键关联的多个电视节目。按值(字母顺序)对字典进行排序,并将结果输出到名为 output_titles.txt 的文件中。因此,如果我的输入文件是“file1.txt”并且该文件的内容是:
20
Gunsmoke
30
The Simpsons
10
Will & Grace
14
Dallas
20
Law & Order
12
Murder, She Wrote
文件 output_keys.txt 应包含:
10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke; Law & Order
30: The Simpsons
并且文件 output_title.txt 包含:
Dallas
Gunsmoke
Law & Order
Murder, She Wrote
The Simpsons
Will & Grace
我的代码工作得很好,我的作业评分很好,除了带有“output_titles.txt”的部分我在代码中写的东西没有按字母顺序排列,我不知道从哪里开始这里。 我的代码是:
inputFilename = input()
keysFilename = 'output_keys.txt'
titlesFilename = 'output_titles.txt'
shows = {}
with open(inputFilename) as inputFile:
showData = inputFile.readlines()
record_count = int(len(showData) / 2)
for i in range(record_count):
seasons = int(showData[2 * i].strip())
showName = showData[2 * i + 1].strip()
if seasons in shows:
shows[seasons].append(showName)
else:
shows[seasons] = [showName]
with open(keysFilename, 'w') as keysFile:
for season in sorted(shows):
keysFile.write(str(season) + ': ')
keysFile.write('; '.join(shows[season]) + '\n')
with open(titlesFilename, 'w') as titlesFile:
for show_list in sorted(shows.values()):
for show in show_list:
titlesFile.write(show + "\n")
我附上了一张我收到通知的问题的图片:1
【问题讨论】:
标签: python sorting alphabetical-sort