Python 列表中列表 ("Stuck")

Python List in List ("Stuck")

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 等子集下的列表中?

比直接回答您的问题更好的答案是:您没有。对于这种情况,您肯定需要一本字典(除非您的程序发展到您更愿意创建自定义对象的程度)

作为一个简单的演示:

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  million'

:

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

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

   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