gpt4 book ai didi

python - 如何跨函数传递变量?

转载 作者:IT老高 更新时间:2023-10-28 21:54:57 26 4
gpt4 key购买 nike

我想在不同函数之间传递值(作为变量)。

例如,我在一个函数中为列表赋值,然后我想在另一个函数中使用该列表:

list = []

def defineAList():
list = ['1','2','3']
print "For checking purposes: in defineAList, list is",list
return list

def useTheList(list):
print "For checking purposes: in useTheList, list is",list

def main():
defineAList()
useTheList(list)

main()

我希望这样做如下:

  1. 将'list'初始化为空列表;调用 main(至少,我知道我做对了……)
  2. 在defineAList()中,给列表赋值;然后将新列表传回 main()
  3. 在 main() 中,调用 useTheList(list)
  4. 由于 'list' 包含在 useTheList 函数的参数中,我希望 useTheList 现在将使用由 defineAList() 定义的列表,而不是调用 main 之前定义的空列表。

但是,我的输出是:

For checking purposes: in defineAList, list is ['1', '2', '3']
For checking purposes: in useTheList, list is []

“return”没有达到我的预期。它实际上是做什么的?如何从 defineAList() 中获取列表并在 useTheList() 中使用它?

我不想使用全局变量。

最佳答案

这就是实际发生的事情:

global_list = []

def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list

def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list

def main():
# returned list is ignored
returned_list = defineAList()

# passed_list inside useTheList is set to global_list
useTheList(global_list)

main()

这就是你想要的:

def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list

def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list

def main():
# returned list is ignored
returned_list = defineAList()

# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)

main()

你甚至可以跳过临时的returned_list,直接将返回值传递给useTheList:

def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())

关于python - 如何跨函数传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16043797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com