我正在为这个学校开展这个项目,我似乎无法完成它。我得到了大部分工作,但有两件事我正在努力。经过几个小时的谷歌搜索和尝试各种不同的解决方法后,我决定我需要寻求帮助。(Python 3)用字典和列表对电影进行排序
def main():
movieCollectionDict = {"Munich":[2005, "Steven Spielberg"],
"The Prestige": [2006, "Christopher Nolan"],
"The Departed": [2006, "Martin Scorsese"],
"Into the Wild": [2007, "Sean Penn"],
"The Dark Knight": [2008, "Christopher Nolan"],
"Mary and Max": [2009, "Adam Elliot"],
"The King\'s Speech": [2010, "Tom Hooper"],
"The Help": [2011, "Tate Taylor"],
"The Artist": [2011, "Michel Hazanavicius"],
"Argo": [2012, "Ben Affleck"],
"12 Years a Slave": [2013, "Steve McQueen"],
"Birdman": [2014, "Alejandro G. Inarritu"],
"Spotlight": [2015, "Tom McCarthy"],
"The BFG": [2016, "Steven Spielberg"]}
promptForYear = True
while promptForYear:
yearChoice = int(input("Enter a year between 2005 and 2016:\n"))
if yearChoice<2005 or yearChoice>2016:
print("N/A")
else:
for key, value in movieCollectionDict.items():
if value[0] == yearChoice:
print(key + ", " + str(value[1]))
promptForYear = False
menu = "MENU" \
"\nSort by:" \
"\ny - Year" \
"\nd - Director" \
"\nt - Movie title" \
"\nq - Quit\n"
promptUser = True
while promptUser:
print("\n" + menu)
userChoice = input("Choose an option:\n")
if userChoice == "q":
promptUser = False
elif userChoice=="y":
for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])):
print (value[0],end=':\n')
print("\t"+key + ", " + str(value[1])+"\n")
elif userChoice == "d":
for key, value in sorted(movieCollectionDict.items(), key=lambda key_value: key_value[1][1]):
print(value[1],end=':\n')
print("\t" + key + ", " + str(value[0])+"\n")
elif userChoice == "t":
for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[0], item[1])):
print(key,end=':\n')
print("\t" + str(value[1]) + ", " + str(value[0])+"\n")
else:
print("Invalid input")
main()
基本上我有一个问题,当我把2006年。而不是显示从那一年两部电影它打印他们两次。我在哪里出错了?
我还有一个问题,在菜单回来之前最后有一个额外的空格,它应该有一个空格,但它当前会打印两个空行。
这是输出:
2005:
Munich, Steven Spielberg
2006:
The Prestige, Christopher Nolan
2006:
The Departed, Martin Scorsese
2007:
Into the Wild, Sean Penn
2008:
The Dark Knight, Christopher Nolan
我既需要从2006年的电影在一起,不分开。
这里是额外的空间的例子:
2016:
The BFG, Steven Spielberg
MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit
Choose an option:
任何帮助都将非常感激!
可能重复的[Python字典,如何保持键/值的声明相同的顺序?](https://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-与宣布的顺序相同) –
您可能会更好地使用元组列表而不是字典。更有效的算法和检索方便的是使用一个完整的关系表按照https://stackoverflow.com/questions/973481/dynamic-table-creation-and-orm-mapping-in-sqlalchemy(那么你'将能够以SQL查询的形式实现所有命令,并以您喜欢的方式(分组和全部)正确地获得结果,但对于您的任务而言,这可能是一种矫枉过正的行为。 –