Python 在不同函数中使用字符串的名称

Python 在不同函数中使用字符串的名称,python,string,function,Python,String,Function,我需要使用第二个函数中第一个函数的movies\u list。我该怎么做 def movie(): movies_list = [movie.strip() for movie in movies_list] movie_explorer() def rand(): rand_item = print(random.choice(movies_list)) 好人 使用返回和参数 def movie(): movies_list = [movie.strip()

我需要使用第二个函数中第一个函数的movies\u list。我该怎么做

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

def rand():
    rand_item = print(random.choice(movies_list))
好人 使用返回和参数

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))
当调用rand时,记住调用函数

rand(movie())
坏的 加行

global movies_list
作为两个函数中的第一行

丑八怪呢 您可以使用可用的globals对象。在这里添加它来完成押韵

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)
好人 使用返回和参数

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))
当调用rand时,记住调用函数

rand(movie())
坏的 加行

global movies_list
作为两个函数中的第一行

丑八怪呢 您可以使用可用的globals对象。在这里添加它来完成押韵

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)

将这两个函数放在一个类中,并使movies\u列出一个类变量。

将这两个函数放在一个类中,并使movies\u列出一个类变量。

将第二个函数嵌套在第一个函数上,这里有一个示例:

def hello():
    a = "hello"
    def world():
        return "%s world" % a
    return world()
print hello()

将第二个函数嵌套在第一个函数上,这里有一个示例:

def hello():
    a = "hello"
    def world():
        return "%s world" % a
    return world()
print hello()

为什么不让它成为一个功能呢?电影不带任何变数。糟糕的例子,因为连电影都不行。试着调用它,你就会明白。为什么不让它成为一个函数呢?电影不带任何变数。糟糕的例子,因为连电影都不行。试着打电话,你就会明白。为什么要上课?那太复杂了。什么是复杂的课程?为什么是课程?那太复杂了。上课有什么复杂的?