首页 > 解决方案 > 将函数内部的元组转换为全局值

问题描述

我正在尝试将文本文件的文本转换为元组。我是一名 Python 初学者,并假设这段代码不会像它可能的那样直接,而且对我来说没问题(现在)。我要做的就是使元组 numbers_bank 成为全局值,这样我就可以在函数之外访问它。

从函数内部打印元组有效,但在函数外部不起作用。

有人可以告诉我我做错了什么吗? (要求输出是一个元组,否则我会将其更改为列表并仅附加元素。)

global numbers_bank

def read_numbers():

    file = open("numbers.txt")
    num = file.read().split(",")
    num_new = [s.replace("[", "") for s in num]
    numbers_bank = [a.replace("]", "") for a in num_new]
    tuple(numbers_bank)

read_numbers()
print(numbers_bank)

标签: pythontuplesglobal

解决方案


这就是 global 关键字的工作方式:https ://www.programiz.com/python-programming/global-keyword

在您的情况下,它将是:

numbers_bank = None

def read_numbers():
    global numbers_bank

    file = open("numbers.txt")
    num = file.read().split(",")
    num_new = [s.replace("[", "") for s in num]
    numbers_bank = [a.replace("]", "") for a in num_new]
    tuple(numbers_bank)  # Note: this doesn't do anything

read_numbers()
print(numbers_bank)

但是,应该避免使用全局变量。相反,您应该通过以下方式使函数返回数字银行:

def read_numbers():
    file = open("numbers.txt")
    num = file.read().split(",")
    num_new = [s.replace("[", "") for s in num]
    numbers_bank = [a.replace("]", "") for a in num_new]
    return tuple(numbers_bank)  # Now the 'tuplified' version of numbers_bank will be used for something because it is returned by the function

numbers_bank = read_numbers()
print(numbers_bank)

另请注意,'tuple(numbers_bank)' 行没有做任何事情,因为您没有将它分配给任何变量。


推荐阅读