【问题标题】:Dictionary Help! Extracting values and making a table字典帮助!提取值并制作表格
【发布时间】:2013-10-24 23:45:34
【问题描述】:

这是我应该编写代码的问题:

为一个函数 showCast 编写合同、文档字符串和实现,该函数接受一个电影标题并按照字符的字母顺序从给定的电影中打印出具有相应演员/女演员的字符。列必须对齐(演员/女演员姓名前 20 个字符(包括角色姓名)。)如果找不到电影,则会打印出错误消息。

它举例说明了这里应该发生的事情

>>> showCast("Harry Potter and the Sorcerer's Stone")

Character           Actor/Actress

----------------------------------------

Albus Dumbledore    Richard Harris

Harry Potter        Daniel Radcliffe

Hermione Granger    Emma Watson

Ron Weasley         Rupert Grint



>>> showCast('Hairy Potter')

No such movie found

以下是我为同一个项目编写的其他函数,它们可能有助于回答这个问题。到目前为止,我必须做的一个总结是,我正在创建一个名为 myIMDb 的字典,其中包含电影标题的键和另一个字典的值。在 that 字典中,键是电影的角色,值是演员。我已经用它做了一些事情。 myIMDb 是记录的全局变量。

其他函数,他们做的是docString

def addMovie (title, charList, actList):
    """The function addMovie takes a title of the movie, a list of characters,
    and a list of actors. (The order of characters and actors match one
    another.) The function addMovie adds a pair to myIMDb. The key is the title
    of the movie while the value is a dictionary that matches characters to
    actors"""

    dict2 = {}
    for i in range (0, len(charList)):
        dict2 [charList[i]] = actList[i]
    myIMDb[title] = dict2
    return myIMDb

我添加了三部电影,

addMovie("Shutter Island", ["Teddy Daniels", "Chuck Aule"],["Leonardo DiCaprio, ","Mark Ruffalo"])

addMovie("Zombieland", ["Columbus", "Wichita"],["Jesse Eisenberg, ","Emma Stone"])

addMovie("O Brother, Where Art Thou", ["Everett McGill", "Pete Hogwallop"],["George Clooney, ","John Turturro"])



def listMovies():
    """returns a list of titles of all the movies in the global variable myIMDb"""

    return (list(myIMDb.keys()))


def findActor(title, name):
    """ takes a movie title and a character's name and returns the
    actor/actress that played the given character in the given movie. If the
    given movie or the given character is notfound, it prints out an error
    message"""
    if title in myIMDb:
        if name in myIMDb[title]:
            return myIMDb[title][name]
        else:
            return "Error:  Character not in Movie"
    else:
        return "Error: No movie found"

现在我遇到了麻烦

我应该编写 showCast 函数,但我遇到了很多麻烦。我已经修补了一段时间,但是当我调用 myIMDb.values() 时,一切都会返回。而且我似乎无法遍历它来对它们进行排序以创建表格。

这是我目前为止的想法,但它并没有达到我的预期。我只是希望你们中的一个可以引导我朝着正确的方向前进。 (注释掉的区域是我之前所做的,只是为了让你可以看到我的思路。[print(alist) 和 print(alist[0]) 只是为了确认它是列表中的一个大条目,而不是完全分开])

def showCast(title):

    if title in myIMDb:
        actList=[]
        chList=[]
        aList = myIMDb[title]
        print (aList)

          """"for i in range (len(aList)):
              if i%2==0:
                  chList.append(aList[i])
              else:
                  actList.append(aList[i])
          print(chList)
          print(actList)""""

else:
    return "Movie not Found"

【问题讨论】:

    标签: python list dictionary spacing


    【解决方案1】:

    首先,我认为您不应该在 addMovie 函数中返回任何内容。只需简单地将其添加到全局变量中:

    myIMDb = {}
    
    def addMovie (title, charList, actList):
        global myIMDb
    
        """The function addMovie takes a title of the movie, a list of characters,
        and a list of actors. (The order of characters and actors match one
        another.) The function addMovie adds a pair to myIMDb. The key is the title
        of the movie while the value is a dictionary that matches characters to
        actors"""
    
        dict2 = {}
        for i in range (0, len(charList)):
            dict2 [charList[i]] = actList[i]
        myIMDb[title] = dict2
    

    虽然我不建议经常使用全局变量,但我认为在这种情况下是可以原谅的 :D

    在那之后,在你的 showCast 函数中,我会使用这个:

    def showCast(title):
        if title in myIMDb:
            actList=[]
            chList=[]
            movie = myIMDb[title]
            for character, cast in movie.keys(), movie.values(): #grab the character from
            #the keys, and cast from the values. 
                  chList.append(character)
                  actList.append(cast)
    
            print (chList, actList)
        else:
            return "Movie not Found"
    

    这是我的输出:

    ['Columbus', 'Jesse Eisenberg, '] ['Wichita', 'Emma Stone']
    

    按预期工作,希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      也许这些 sn-ps 可以帮助你:

      打印表格行

      def printRow(character, actor):
          print(character + (20 - len(character)) * ' ' + actor))
      

      对字符进行排序

      def getSortedTitleList(titleList):
          sortedList = []
          characters = sorted(titleList)
          for character in characters:
              sortedList.append((character, titleList[character]))
          return sortedList
      

      注意:我将 dict.keys().sort() 更改为 sorted(dict) 以兼容 Python 3。

      【讨论】:

      • 这很有意义,我感谢您的帮助。但它说我无法对 dict.keys 进行排序。所以我不能对字符进行排序?
      • 好的,这在 Python 3 中发生了变化。我正在使用 Python 2 进行测试。我将更改代码以使用 Python 3。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2010-11-14
      • 2016-09-24
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多