列表中的Python列表(" Stuck")

时间:2015-02-05 09:43:57

标签: python python-3.x

def lists(): #Where list is stored
    List = ["Movie_Name",[""],"Movie_Stars",[""],"Movie_Budget",[""]] 

    print ("Your Movies")

    amount_in_list = int(input("How many Movies? "))
    x = 1
    while x <= amount_in_list:
        film = input ("Name of film ... ")
        stars = input ("Main stars ...")
        Budget = input ("Budget ...")
        List.append["Movie_Name"](film)
        List.append["Movie_Stars"](stars)
        List.append["Movie_Budget"](Budget)

lists()

如何将您输入的电影添加到子集化Movie_Name等下的列表中?

2 个答案:

答案 0 :(得分:2)

比直接回答问题的答案更好的答案是:你没有。你肯定需要一个字典来解决这种情况(除非你的程序发展到你更喜欢创建自定义对象的程度)

作为一个简单的演示:

def getMovies():

    movieinfo = {"Movie_Name": [], "Movie_Stars": [], "Movie_Budget": []}
    print ("Your Movies")
    amount_in_list = int(input("How many Movies? "))

    x = 1
    while x <= amount_in_list:
        film = input ("Name of film ... ")
        stars = input ("Main stars ...")
        budget = input ("Budget ...")
        movieinfo["Movie_Name"].append(film)
        movieinfo["Movie_Stars"].append(stars)
        movieinfo["Movie_Budget"].append(budget)
        x+=1

    return movieInfo

请注意,使用dict只需使用key字符串即可获取相应的列表(在函数开头初始化)并根据需要附加数据。

已编辑以提供有关OP更新请求的更多信息。

如果您想根据用户提供的电影名称查找电影的信息,您可以尝试这样的事情:

film = 'The Matrix' # Assuming this is the user's input.

Try:
    # The index method will throw an exception if
    # the movie cannot be found. If that happens,
    # the 'except' clause will execute and print
    # the relevant statement.
    mIdx = movieinfo['Movie_Name'].index(film)

    print '{0} stars {1} and had a reported budget of {2}'.format(
        film, movieInfo['Movie_Stars'][mIdx], movieInfo['Movie_Budget'][mIdx])

except ValueError:
   print '{0} is not in the movie archives. Try another?'.format(film)

<强>输出

'The Matrix stars Keanu Reeves and had a reported budget of $80 million'

'The Matrix is not in the movie archives. Try another?'

答案 1 :(得分:1)

我会将电影信息存储在一个对象中。这样,您的代码将更容易扩展,进行更改和重用。您可以轻松地向您的电影类添加方法来执行自定义内容或添加更多属性,而无需更改代码。

   class Movie:
        def __init__(self, name='', actors=[], rating=0 budget=0):
            self.name=name
            self.actors=actors
            self.budget=budget
            self.rating=rating

        def setName(self, newname):
            self.name=newname

        def setActors(self, newstars):
            self.actors=newstars

        def setBudget(self, newbudget):
            self.budget=newbudget

        def setRating(self, newrating):
            self.rating=newrating

    # example
    mymovies=[]

    movie1= Movie('Interstellar',['actor1','actor2','actor3'], 5, 100000)


    movie2=Movie()
    movie2.setName('other movie')
    movie2.setActors(['actor1','actor2','actor3'])
    movie2.setBudget(10000)

    mymovies.append(movie1)
    mymovies.append(movie2)
    # or append to your list in a loop