Using name of strings in different functions

后端 未结 3 1349
旧巷少年郎
旧巷少年郎 2021-01-24 22:57

I need to use movies_list from the first function in the second. How do I do that?

def movie():
    movies_list = [movie.strip() for movie in movies         


        
相关标签:
3条回答
  • 2021-01-24 23:40

    Make the second function nested on the first one, here you have an example:

    def hello():
        a = "hello"
        def world():
            return "%s world" % a
        return world()
    print hello()
    
    0 讨论(0)
  • 2021-01-24 23:56

    put the two functions in a class, and make movies_list a class variable.

    0 讨论(0)
  • 2021-01-24 23:57

    The Good

    Use return and arguments

    def movie():
        movies_list = [movie.strip() for movie in movies_list]
        movie_explorer()
        return movies_list
    
    def rand(movies_list):
        rand_item = print(random.choice(movies_list))
    

    And when calling rand remember to call the function as

    rand(movie())
    

    The Bad

    Add a line

    global movies_list
    

    as the first line in both functions

    And the Ugly

    You can make use of the globals object available. (Adding it here to complete the rhyme)

    def movie():
        global movie_returns
        movie_returns = [movie.strip() for movie in movies_list]
        movie_explorer()
        # No return
    
    def rand():  # No argument
        movies_list = next((globals()[v] for v in globals() if v=='movies_return'))
        rand_item = random.choice(movies_list)
    
    0 讨论(0)
提交回复
热议问题