如果需要在python函数中清空全局列表变量,很多开发人员的第一反应也许会是:
lst1 = []
lst2 = []
def clean_list():
lst1 = []
lst2 = []
但是在python的体系中,这会导致函数重新定义了作用域在函数体内的新的局部变量,和在全局作用域中定义的全局变量,即使名称相同,也会是指向不同地址的完全不想干的两个变量。那么有什么办法去解决呢?提供4个方法,欢迎补充!
1、将列表变量作为入参传进去
lst1 = []
lst2 = []
def clean_list(lst1, lst2):
lst1 = []
lst2 = []
2、python 3.x版本中list变量新增了clear函数(python 2.x版本不支持)
lst1 = []
lst2 = []
def clean_list():
lst1.clear()
lst2.clear()
3、 python 2.x版本中支持del
lst1 = []
lst2 = []
def clean_list():
del lst1[:]
del lst2[:]
4、即使用global去声明函数体内的这个变量是全局变量
lst1 = []
lst2 = []
def clean_list():
# note that you can't write code as this:
# global lst1 = [] ....
global lst1
global lst2
lst1 = []
lst2 = []