我正在尝试将文本文件的文本转换为元组。我是一名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)
答案 0 :(得分:1)
全局关键字的工作方式如下: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)'行没有任何作用,因为您尚未将其分配给任何变量。
答案 1 :(得分:0)
您的要求:
FORMAT()
您应该怎么做:
>>> def read_numbers():
...: global numbers_bank
...: # do stuff
...: numbers_bank = [1, 2, 3] # create some list
...: numbers_bank = tuple(numbers_bank)
>>> read_numbers()
>>> numbers_bank
(1, 2, 3)
在函数中更改全局状态可能会变得混乱并且很难很快理解。 >>> def read_numbers():
...: # do stuff
...: numbers_bank = [1, 2, 3] # create some list
...: numbers_bank = tuple(numbers_bank)
...: return numbers_bank
>>> numbers_bank = read_numbers()
>>> numbers_bank
(1, 2, 3)
可以使您更方便地从函数中计算出值,然后在可能的情况下为该返回值显式分配一个名称。
还请注意,使用return
而不是使用列表理解,然后将tuple(generator-expression)
构造函数应用于理解结果(即
tuple