首页 > 解决方案 > 尝试在python中为全局变量赋值时出现问题

问题描述

我正在尝试为python中名为“give_total_list”的函数内的全局列表分配一个值

total_list = list()

def give_total_list():
    global total_list //should I define the global variable here?
    big_list = glob.glob("drebin/feature_vectors/*")
    name_list = list()
    for el in big_list:
        single_directory_list = el.split("/")
        name = single_directory_list[2]
        name_list.append(name)

    total_list = list(name_list) 


def main():
   print (total_list)
   #when I print the list, it's void.

我该如何解决这个问题?

标签: pythonlistglobal

解决方案


尝试这个:

total_list = list()

def give_total_list():
    global total_list //should I define the global variable here?
    big_list = glob.glob("drebin/feature_vectors/*")
    name_list = list()
    for el in big_list:
        single_directory_list = el.split("/")
        name = single_directory_list[2]
        name_list.append(name)

    total_list = list(name_list) 


def main():
   global total_list
   give_total_list() #<<<<<<<<<<<<<<<
   print (total_list)

main() #<<<<<<<<<<<<<<<<<

一旦你调用你的函数,它应该可以工作。只定义一个函数 (def ....) 只会创建它你仍然必须调用它 main() 例如调用主函数


推荐阅读