在python函数中,我希望对函数中的全局变量使用(读取、查询(if语句检查),然后执行其他语句)。 要在函数中执行此操作,我必须将变量声明为全局变量。 我想给函数传递一个变量,然后使用传递的变量将正确的全局变量声明为全局变量。在
current_data_list = []
current_data_list_length = len(current_data_list)
#the list is filled with each line from a file
def listtousable(listname):
local_list_name = listname
local_list_length = local_list_name + "_length"
global local_list_name
global local_list_length
if local_list_name[0] == "firstlinevariable":
local_list_length = len(local_list_name)
print local_list_length
else:
print "wtf"
#fill into list
listtousable("current_data_list")
如有任何帮助,我们将不胜感激:)
不需要在函数中创建全局状态变量;只需更改其值
休的评论是对的,但如果你还想这么做,你可以:
请参见Python3.6的文档here
编辑
对于Python2.7,请参见here
相关问题 更多 >
编程相关推荐