python - 尝试在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.
我该如何解决这个问题?
解决方案
尝试这个:
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() 例如调用主函数
推荐阅读
- docker - 我可以在 Synology DS418 上安装 Docker 吗?
- reactjs - 错误:不变违规:requireNativeComponent:在 UIManager 中找不到“RNCPicker”
- r - 使用不同的参数值多次运行一个包函数
- kubernetes - StatefulSet 数据一致性
- swift - 如何在 SwiftUI 中刷新 body
- javascript - 从另一个存储切片中的一个存储切片调用一个 redux 操作
- julia - Julia:readdlm 因前导空白而失败
- string - 在 Python2 中替换 `encode()`
- python - 获取数据仅以空格正则表达式开头 - Python
- bixby - 如何制作启动特定应用程序的胶囊?