从字典中打印表格

时间:2013-10-24 17:45:20

标签: python list dictionary spacing

这是我应该编码的问题:

  

编写一个函数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的字典,其中包含电影标题的键,以及另一个字典的值。在那个字典中,键是电影的一个字符,值是actor。而且我已经完成了它的工作。 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 = list(myIMDb.values())
        print (aList)
        print (aList[0])
          """"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"

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但我会采取刺。我认为你的困惑来自于myIMDb对象的嵌套特性。要获取有关特定电影的信息,您应该使用标题作为myIMDb的密钥,例如myIMDb[title]。你得到的是另一个字典,你可以用它来获得字符/演员键值对。

这是showCast函数的工作版本:

def showCast(title):

    if title in myIMDb:
        print("{0:20} {1:20}".format("Character", r"Actor/Actress"))
        print("-"*40)
        for character, actor in myIMDb[title].items():
            print("{0:20} {1:20}".format(character, actor))
    else:
        return "Movie not Found"

第一个print语句生成标题,并使用Python的格式字符串方法获得所需的对齐间距。下一个print语句是分隔符,然后函数的主要部分是使用for循环迭代对。

我希望有所帮助。