Python 函数间传递列表
我在下面的代码中更改了全局变量。我读到的大部分内容都是说远离全球人。。。在下面的示例中,我想使用“生成列表”,然后在“打印列表”中打印它,然后清除列表。我用globals来做这个,关于如何避免globals的建议 我知道我可以在一个函数中添加这些,但这是一个更大函数的一部分,这是我唯一遇到问题的部分。先谢谢你Python 函数间传递列表,python,Python,我在下面的代码中更改了全局变量。我读到的大部分内容都是说远离全球人。。。在下面的示例中,我想使用“生成列表”,然后在“打印列表”中打印它,然后清除列表。我用globals来做这个,关于如何避免globals的建议 我知道我可以在一个函数中添加这些,但这是一个更大函数的一部分,这是我唯一遇到问题的部分。先谢谢你 x_lst = [] def make_lists(): global x_lst x_lst.append("Hello") def print_list():
x_lst = []
def make_lists():
global x_lst
x_lst.append("Hello")
def print_list():
global x_lst
for i in x_lst:
print(i)
x_lst = []
def main():
make_lists()
print_list()
if __name__ =="__main__":
main()
为了避免使用global,您必须在函数声明中使用
return
关键字来返回一个值,在本例中,该值将是您新创建的列表。您还必须在函数声明中使用参数
,这些参数是函数中值的占位符。因此,不需要全局值的原因是,您正在将列表从一个函数传递到另一个函数
def make_lists():
return ['Hello'] # Your are creating the list with a single value,
# and return it
def print_list(ls):
for i in ls: # You are iterating thru the list,
print(i) # which is the input of this function
def main():
print_list(make_lists()) # In your main function you call the make_list()
# which will return the newly created list, and
# pass it to print_list, which will iterate thru
# the list and prints your values out
if __name__ =="__main__":
main()
为了避免使用global,您必须在函数声明中使用
return
关键字来返回一个值,在本例中,该值将是您新创建的列表。您还必须在函数声明中使用参数
,这些参数是函数中值的占位符。因此,不需要全局值的原因是,您正在将列表从一个函数传递到另一个函数
def make_lists():
return ['Hello'] # Your are creating the list with a single value,
# and return it
def print_list(ls):
for i in ls: # You are iterating thru the list,
print(i) # which is the input of this function
def main():
print_list(make_lists()) # In your main function you call the make_list()
# which will return the newly created list, and
# pass it to print_list, which will iterate thru
# the list and prints your values out
if __name__ =="__main__":
main()
我对您的代码做了最小的更改,说明了如何传递列表,而不是使用全局变量。希望这有助于澄清
def make_lists(x_lst):
x_lst.append("Hello")
def print_list(x_lst):
for i in x_lst:
print(i)
def main():
x_lst = []
make_lists(x_lst)
print_list(x_lst)
if __name__ =="__main__":
main()
我对您的代码做了最小的更改,说明了如何传递列表,而不是使用全局变量。希望这有助于澄清
def make_lists(x_lst):
x_lst.append("Hello")
def print_list(x_lst):
for i in x_lst:
print(i)
def main():
x_lst = []
make_lists(x_lst)
print_list(x_lst)
if __name__ =="__main__":
main()
使用参数将数据传递到函数中,并使用返回值将数据传递出去
用参数将数据传递到函数中,用返回值将数据传递出去。下面是我的简单建议,为什么不给函数输入呢。传递一个要打印的列表而不是使用全局变量是一个简单的选择。如果您正在寻找保持特定作用域状态的方法,可以尝试将这些函数放入类中(换句话说,使用OOP)
全局变量的问题在于,当您将“x_lst”声明为全局变量时,它会将“x_lst”打开到函数外部,这可能不是或不是您的预期目标。我的简单建议是,为什么不给函数输入。传递一个要打印的列表而不是使用全局变量是一个简单的选择。如果您正在寻找保持特定作用域状态的方法,可以尝试将这些函数放入类中(换句话说,使用OOP) 全局变量的问题是,当您将“x_lst”声明为全局变量时,它会将“x_lst”打开到函数外部,这可能不是或不是您的预期目标