下面是我應該代碼的問題:字典幫助!提取值,使表
寫一個函數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的字典,其中包含電影標題的關鍵字以及另一個字典的值。在即字典中,鍵是電影的角色,而價值是演員。我已經做了它的東西。 myIMDb是記錄的全局變量。
其他功能方面,他們做的是文檔字符串
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"
這樣做很有意義,我感謝您的幫助。但它說我不能排序dict.keys。所以我不能排序字符? – Jonerhan
好的,在Python 3中發生了變化。我正在測試Python 2.我將更改代碼以使用Python 3。 –