很抱歉这个简单的(希望)问题:
我的代码:
end_result = []
def func():
end_result = []
data= [1,2,3,4,5,6,7,8,9]
for i in data:
if i not in end_result:
end_result.append(i)
func()
print(end_result)
在函数顶部添加行 end_result = []
以在添加数据输出之前重置列表:
[]
并删除它输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
这是为什么呢?在我的代码中,我需要在向其添加/重新添加信息之前将 end_result = []
重置并清空。或者,是否有另一种方法可以代替我的以下方法来清空列表?(如果需要它才能使代码正常工作)
谢谢你的帮助,也谢谢你容忍我的坏问题哈哈
最佳答案
您可以只使用 global
关键字。
def func():
global end_result
end_result = []
data= [1,2,3,4,5,6,7,8,9]
for i in data:
if i not in end_result:
end_result.append(i)
func()
print(end_result)
但是,返回列表而不是分配给全局变量更有意义。
def func():
end_result = []
data= [1,2,3,4,5,6,7,8,9]
for i in data:
if i not in end_result:
end_result.append(i)
return end_result
res = func()
print(res)
如果 data
也是一个参数而不是局部变量,则该方法的可重用性会更高。
def func(data):
end_result = []
for i in data:
if i not in end_result:
end_result.append(i)
return end_result
res = func([1,2,3,4,5,6,7,8,9])
print(res)
关于python - 附加数据后列表返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68340547/