Skip to main content
 首页 » 编程设计

python之将函数内的元组转换为全局值

2024年12月31日9freeliver54

我正在尝试将文本文件的文本转换为元组。我是一个 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) 

请您参考如下方法:

这是全局关键字的工作原理: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) 

但是,全局变量应该是avoided . 相反,您应该按以下方式使函数返回数字银行:

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)' 行不会执行任何操作,因为您尚未将其分配给任何变量。