2017-10-14 186 views
4

我正在为这个学校开展这个项目,我似乎无法完成它。我得到了大部分工作,但有两件事我正在努力。经过几个小时的谷歌搜索和尝试各种不同的解决方法后,我决定我需要寻求帮助。(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: 

任何帮助都将非常感激!

+0

可能重复的[Python字典,如何保持键/值的声明相同的顺序?](https://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-与宣布的顺序相同) –

+0

您可能会更好地使用元组列表而不是字典。更有效的算法和检索方便的是使用一个完整的关系表按照https://stackoverflow.com/questions/973481/dynamic-table-creation-and-orm-mapping-in-sqlalchemy(那么你'将能够以SQL查询的形式实现所有命令,并以您喜欢的方式(分组和全部)正确地获得结果,但对于您的任务而言,这可能是一种矫枉过正的行为。 –

回答

1

改进:

  1. 分组同年的电影时,用户按年份排序列表。
  2. 当用户按照导演对列表进行排序时,分组了相同导演的电影。
  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 
    first_time = True 
    while promptUser: 
     if first_time == True: 
      print() 
      first_time = False 
     print(menu) 
     userChoice = input("Choose an option:\n") 
     if userChoice == "q": 
      promptUser = False 
     elif userChoice=="y": 
      year_sorted = {}    
      for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])): 
       year = value[0] 
       title = key 
       director = value[1] 
       if year not in year_sorted: 
        year_sorted[year] = [[title, director]] 
       else: 
        year_sorted[year].append([title, director])    
      for year in sorted(year_sorted): 
       print (year,end=':\n') 
       movies = year_sorted[year] 
       for movie in sorted(movies, key = lambda x:x[0]): 
        print("\t"+movie[0] + ", " + movie[1]) 
       print() 
     elif userChoice == "d": 
      director_sorted = {}    
      for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1][1])): 
       year = value[0] 
       title = key 
       director = value[1] 
       if director not in director_sorted: 
        director_sorted[director] = [[title, year]] 
       else: 
        director_sorted[director].append([title, year])    
      for director in sorted(director_sorted): 
       print (director,end=':\n') 
       movies = director_sorted[director] 
       for movie in sorted(movies, key = lambda x:x[0]): 
        print("\t"+movie[0] + ", " + str(movie[1]))    
       print() 
     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() 

输出:

Enter a year between 2005 and 2016: 
2006 
The Prestige, Christopher Nolan 
The Departed, Martin Scorsese 

MENU 
Sort by: 
y - Year 
d - Director 
t - Movie title 
q - Quit 

Choose an option: 
y 
2005: 
    Munich, Steven Spielberg 

2006: 
    The Departed, Martin Scorsese 
    The Prestige, Christopher Nolan 

2007: 
    Into the Wild, Sean Penn 

2008: 
    The Dark Knight, Christopher Nolan 

2009: 
    Mary and Max, Adam Elliot 

2010: 
    The King's Speech, Tom Hooper 

2011: 
    The Artist, Michel Hazanavicius 
    The Help, Tate Taylor 

2012: 
    Argo, Ben Affleck 

2013: 
    12 Years a Slave, Steve McQueen 

2014: 
    Birdman, Alejandro G. Inarritu 

2015: 
    Spotlight, Tom McCarthy 

2016: 
    The BFG, Steven Spielberg 

MENU 
Sort by: 
y - Year 
d - Director 
t - Movie title 
q - Quit 

Choose an option: 
3

这是解决方案。所有更改都在while循环的if条件中。要根据年份/导演/标题对项目进行分组,可以使用变量prev_value。只有当prev_value改变时才打印。这可确保在打印排序数据时进行分组。还要注意换行符的打印。现在他们打印在组页眉之前。这解决了双层空间问题。

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: 
     prev_val = '' 
     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])): 
       if(prev_val!=value[0]): 
        print ("\n",value[0],end=':\n',sep='') 
        prev_val = value[0] 
       print("\t"+key + ", " + str(value[1])) 
     elif userChoice == "d": 
      for key, value in sorted(movieCollectionDict.items(), key=lambda key_value: key_value[1][1]): 
       if(prev_val!=value[1]): 
        print("\n",value[1],end=':\n',sep='') 
        prev_val = value[1] 
       print("\t" + key + ", " + str(value[0])) 
     elif userChoice == "t": 
      for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[0], item[1])): 
       if(prev_val!=key): 
        print("\n",key,end=':\n',sep='') 
        prev_val = key 
       print("\t" + str(value[1]) + ", " + str(value[0])) 
     else: 
      print("Invalid input") 
main() 
1

1:

你的问题是与逻辑。在这里,你会感兴趣的部分。

elif userChoice=="y": 
    prev_years = [] 
    for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])): 
     if value[0] in prev_years: 
      print("\t"+key + ", " + str(value[1])+"\n") 
     else: 
      print (value[0],end=':\n') 
      print("\t"+key + ", " + str(value[1])+"\n") 
     prev_years.append(value[0]) 

通知我添加了一个列表prev_years,我加年,当我第一次看到他们。

我第一次检查2005是否在我的prev_years列表中。但开始它将是空的。因此else部分将执行!

else: 
    print (value[0],end=':\n') 
    print("\t"+key + ", " + str(value[1])+"\n") 

然后我会做到这一点,

prev_years.append(value[0]) 

所以,现在,

prev_years = [2005]

所以,当我看到2006首次我也是这样做的!在我prev_years列表中添加它

所以,现在,

prev_years = [2005,2006]

接下来是招!

看看我的病情,

if value[0] in prev_years: 
    print("\t"+key + ", " + str(value[1])+"\n") 

所以当明年已经是我prev_years列表我只是做了以上。这给你你想要的东西!

2:

参加口译看看这个,

>>> 
>>> print("hello");print("Vishnu") 
hello 
Vishnu 
>>> print("hello"+"\n");print("Vishnu"+"\n") 
hello 

Vishnu 

>>> 

这基本上就是为什么额外的空间。默认情况下,print()在最后放置一个新行。所以删除所有的反斜杠\n的和你有你想要的。

输出:执行

Enter a year between 2005 and 2016: 
2006 
The Prestige, Christopher Nolan 
The Departed, Martin Scorsese 

MENU 
Sort by: 
y - Year 
d - Director 
t - Movie title 
q - Quit 

Choose an option: 
y 
2005: 
    Munich, Steven Spielberg 
2006: 
    The Prestige, Christopher Nolan 
    The Departed, Martin Scorsese 
2007: 
    Into the Wild, Sean Penn 
2008: 
    The Dark Knight, Christopher Nolan 
2009: 
    Mary and Max, Adam Elliot 
2010: 
    The King's Speech, Tom Hooper 
2011: 
    The Artist, Michel Hazanavicius 
    The Help, Tate Taylor 
2012: 
    Argo, Ben Affleck 
2013: 
    12 Years a Slave, Steve McQueen 
2014: 
    Birdman, Alejandro G. Inarritu 
2015: 
    Spotlight, Tom McCarthy 
2016: 
    The BFG, Steven Spielberg 

MENU 
Sort by: 
y - Year 
d - Director 
t - Movie title 
q - Quit 

Choose an option: 
2

让我们先来了解实际的问题:

因此,假设你有一个清单:

a=[(2006,1),(2007,4),(2008,9),(2006,5)] 

而且要将此转换为字典作为元组的第一个元素作为元组的第二个元素。是这样的:

{2008: [9], 2006: [5], 2007: [4]} 

但有你也想,对那些具有不同的值,但按键键同样喜欢(2006,1)赶上和(2006,5)密钥是相同的,但价值是不同的。你想,这些值只有一个键,以便预期输出附加:

{2008: [9], 2006: [1, 5], 2007: [4]} 

对于这类问题,我们做这样的事情:

首先创建一个新的字典,然后我们按照这个模式:

if item[0] not in new_dict: 
    new_dict[item[0]]=[item[1]] 
else: 
    new_dict[item[0]].append(item[1]) 

所以我们首先检查关键是在新的字典,如果它已经然后重复键的值添加到它的价值:

全码:

a=[(2006,1),(2007,4),(2008,9),(2006,5)] 

new_dict={} 

for item in a: 
    if item[0] not in new_dict: 
     new_dict[item[0]]=[item[1]] 
    else: 
     new_dict[item[0]].append(item[1]) 

print(new_dict) 

现在,让我们回到你的问题,你也想这样的事情,所以我们可以这样做:

elif userChoice=="y": 
    new={} 
    for key, value in sorted(movieCollectionDict.items()): 
     for k in value: 
      if value[0] not in new: 
       new[value[0]]=[(key,value[1])] 
      else: 
       new[value[0]].append((key,value[1])) 
    print({key: set(value) for key, value in new.items()}) 

所以全码:

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": 
      new={} 
      for key, value in sorted(movieCollectionDict.items()): 
       for k in value: 
        if value[0] not in new: 
         new[value[0]]=[(key,value[1])] 
        else: 
         new[value[0]].append((key,value[1])) 
      print({key: set(value) for key, value in new.items()}) 

     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() 

PS:你可以格式化输出因为您想要第一行的关键字(年)和第二行的值(电影名称)。

相关问题