Using name of strings in different functions

后端 未结 3 1351
旧巷少年郎
旧巷少年郎 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: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)
    

提交回复
热议问题