LAB:对电视节目(字典和列表)进行分类



我已经使用Pycharm来帮助我纠正这个问题。我试着设定一个特定的范围。每次打印东西时,我都会考虑用户计数+=1,但无法在不出错的情况下将其输入代码。我的输出

07: Rules of Engagement; Medium; Lux Video Theatre
08: Mama; Barney Miller; Castle
10: Will & Grace; Smallville; Modern Family; Friends
11: Cheers; The Jeffersons
12: Murder, She Wrote; NYPD Blue
14: Dallas; Bonanza
15: ER
20: Gunsmoke; Law & Order; Law & Order: Special Victims Unit
30: The Simpsons
''''
expected output
7: Rules of Engagement; Medium; Lux Video Theatre
8: Mama; Barney Miller; Castle
10: Will & Grace; Smallville; Modern Family; Friends
11: Cheers; The Jeffersons
12: Murder, She Wrote; NYPD Blue
14: Dallas; Bonanza
15: ER
20: Gunsmoke; Law & Order; Law & Order: Special Victims Unit
30: The Simpsons
'''

''

file = input() #user file input
with open(file) as f: #open file 
data = f.readlines()
dict_info = {}
for i in range(0, len(data)-1, 2): 
season = data[i].strip()
name = data[i+1].strip()
if(season in dict_info):
dict_info[season].append(name)
else:
dict_info[season] = [name]
#OUTPUT KEYS
keys = list(dict_info.keys()) #will list the dictionary keys
keys.sort() #will sort the keys from min to max
with open('output_keys.txt', 'w') as f:
for key in keys:
names = '; '.join(name for name in dict_info[key]) #will print the name with number 
f.write(str(key)+': '+names+"n")
names = [] #Dictionary value
for item in dict_info: #will add name to dict
for name in dict_info[item]:
names.append(name) 
#OUTPUT TITTLE
names.sort() #sort names from min to max
with open('output_titles.txt', 'w') as f: #open the file
for name in names: #will write name plus a new line
f.write(name+'n')

在第6行中,您应该将变量season指定为整数。

season = int(data[i].strip())

这将删除输出中7和8之前的0。

这是我刚刚为这个实验室写的一些代码。这个程序通常比我在这里发布的其他程序长,但这个实验室可能会让那些没有介绍漂亮打印等功能的初学者感到害怕。因此,我试图利用他们班上迄今为止学到的知识来简化每个需求。字典是一种映射类型,但实验室要求您生成一个既有映射又有序列的字典。

# Dictionary to store channels and their respective shows.
my_dict = {}
# Dictionary that results from sorting my_dict.
sorted_dict = {}
# A list used to sort the titles for test 3.
sorted_list = []
# Opening the file declared from input in read-only.
f1 = open(input(), 'r')
# contents is a list of strings where the first element is the first line of input and so forth.
contents = f1.readlines()
# Close the file as soon as it is no longer needed.
f1.close()
# A step of 2 is used so an out-of-range index error does not occur at EOF.
for i in range(0, len(contents), 2):
# Through each iteration, key is assigned with the numbers within the file.
# Using int() eliminates the 'n' you would normally see in output involving each line.
key = int(contents[i])
# value is the line after each number in the file. Example: "Dallas" would be value if key is 14.
# This is because [i + 1] grabs the line following the current line in the iteration the loop is in.
# strip() removes the newline similar to int()
value = contents[i+1].strip()

# Add value to sorted_list so it can be sorted at the end of the loop.
sorted_list.append(value)

# If a key already exists in my_dict.
# In the example: this statement will activate when the 2nd iteration of '20' reaches this point.
if key in my_dict:
# In the example: my_dict[key] = 'Gunsmoke' and value = 'Law & Order'.
# Therefore, 20 is assigned with 'Gunsmoke; Law & Order'.
my_dict[key] = my_dict[key] + '; ' + value
# If a key does not exist in my_dict AKA the key only occurs once in the file:
else:
my_dict[key] = value
# Sort the list after the loop in ascii order.
sorted_list.sort()
# In example: sorted(my_dict) = ['10', '12', '14', '20', '30'].
# sorted_key iterates through each element in numerical order.
for sorted_key in sorted(my_dict):
# In example: sorted_dict[10] = my_dict[10] = "Will & Grace"
# Remember to use the str() feature to prepare the key for being written on a file.
sorted_dict[str(sorted_key)] = my_dict[sorted_key]
# Opens "output.keys.txt" in write-only.
f2 = open("output_keys.txt", 'w')
# The for loop iterates through each key-value pair in sorted_dict for proper writing formatting to the file.
for key, value in sorted_dict.items():

# We do not need to convert any variables to a string, but we must use a newline at the end of each write.
# Do not be afraid to test your output with a print() statement before writing.
f2.write(key + ": " + value + 'n')
# Closes the file after being written.
f2.close()
# Opens "output.titles.txt" in write-only.
f3 = open("output_titles.txt", 'w')
# Iterates through every value of sorted_list
for value in sorted_list:
f3.write(value + 'n')
# Closes the file after being written.
f3.close()

很久以前,当我第一次做这个实验室时,我有点作弊,按顺序输出字典的内容,而不是对字典进行排序。我很幸运,我的教授对我很宽容,不管怎样都给了我满分。

此代码应该可以工作并获得完整的10/10。在编写代码时,我一直忘记去掉多余的数字,但我在output_file += d_key.lstrip('0') + ': '行中发现需要去掉这些数字。

file_name = input()
user_file = open(file_name)
input_list = user_file.readlines()

my_diction = {}
for index in range (len(input_list)):
if index % 2 == 0:
diction_key = input_list[index].strip('n')
if diction_key not in my_diction:
my_diction[diction_key] = []
else:
my_diction[diction_key].append(input_list[index].strip('n'))


sorted_keys = sorted(my_diction.keys())
output_file = ''
tv_show_list = []
for d_key in sorted_keys:
output_file += d_key.lstrip('0') + ': '
for tvshow in my_diction[d_key]:
output_file += tvshow + '; '
tv_show_list.append(tvshow)
output_file = output_file[:-2] + 'n'
print(output_file)
file = open("output_keys.txt", "w")
file.write(output_file)
file.close()

tv_show_list.sort()
sorted_list = ''
for tv_show in tv_show_list:
sorted_list += tv_show + 'n'
print(sorted_list)
file = open("output_titles.txt", "w")
file.write(sorted_list)
file.close()

在我的LAB 4.9.1中,对于这个特定的练习,预期的输出顺序相反。这是我用来通过颠倒密钥和名称变量的排序顺序来完成全额学分分配的代码:


file = input() # file input
with open(file) as f: #open file
data = f.readlines()
dict_info = {}
for i in range(0, len(data)-1, 2):
season = int(data[i].strip())
name = data[i+1].strip()
if(season in dict_info):
dict_info[season].append(name)
else:
dict_info[season] = [name]
#OUTPUT KEYS
keys = list(dict_info.keys()) #will list the dictionary keys
keys.sort() #will sort the keys
with open('output_keys.txt', 'w') as f:
for key in reversed(keys): #reverses the sort order for output
names = '; '.join(name for name in dict_info[key]) #will print the name with number
f.write(str(key)+': '+names+"n")
names = [] #Dictionary value
for item in dict_info: #will add name to dict
for name in dict_info[item]:
names.append(name)
#OUTPUT TITLE
names.sort() #sort names
with open('output_titles.txt', 'w') as f: #open the file
for name in reversed(names): #reverses the sort order for output
f.write(name+'n') #will write name plus a new line
file_name = input()
tv_shows = {}

with open(file_name, 'r') as f:
info = f.readlines()

for i in range(0, len(info), 2):
season =info[i].strip()
show = info[i+1].strip()
if season in tv_shows:
tv_shows[season].append(show)
else:
tv_shows[season] = [show]
keys = list(tv_shows.keys())
keys.sort(reverse=True)
with open('output_keys.txt', 'w') as f:
for key in keys:
names = '; '.join(x for x in tv_shows[key])
f.write(f'{str(int(key))}: {names}n')
names = []
for i in tv_shows:
for j in tv_shows[i]:
names.append(j)
names.sort(reverse=True)

with open('output_titles.txt', 'w') as f:
for i in names:
f.write(f'{i}n')

最新更新