python - 将函数内部的元组转换为全局值
问题描述
我正在尝试将文本文件的文本转换为元组。我是一名 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)
解决方案
这就是 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)' 行没有做任何事情,因为您没有将它分配给任何变量。
推荐阅读
- google-cloud-storage - Google pubsub 侦听器未收到所有消息
- java - 如何解决 java.lang.ClassNotFoundException: org.aspectj.lang.ProceedingJoinPoint 异常?
- css - 重用组件时,我的 CSS 没有应用到它
- css - 找不到角度资产静态文件
- javascript - 再次出现错误“SyntaxError”,但现在我按照我过去问题的答案
- python-3.x - 如何访问存储在 Google Cloud Storage 中的 jpeg 文件?
- keras - 图像回归:正方形的宽度
- c# - 通过列表框项目选择c#更改复选框的状态
- flutter - 在构建中获取 context.read() 功能
- vb6 - 将 DateValue() 与 datetime2 一起使用时类型不匹配