我有大量的列表和字典,它们需要在每次迭代中清除。我试图写一个函数的GlobalClear,其中有一个列表包含着要清除的列表或字典名称。
Result1={"d11":"1","d12":"2"}
Result2 =["l11","l22"]
def length(name):
print(str(name) + " having length is : "+ str(len(name)))
def GlobalClear():
overallList = ["Result1", "Result2"]
for key in overallList:
list(key).clear()
length(list(key))
print("Prev Length")
length(Result1)
length(Result2)
GlobalClear()
print("Final Length")
length(Result1)
length(Result2)
输出: Prev Length
{'d11': '1', 'd12': '2'} having length is : 2
['l11', 'l22'] having length is : 2
['R', 'e', 's', 'u', 'l', 't', '1'] having length is : 7
['R', 'e', 's', 'u', 'l', 't', '2'] having length is : 7
Final Length
{'d11': '1', 'd12': '2'} having length is : 2
['l11', 'l22'] having length is : 2
预期输出: Prev Length
{'d11': '1', 'd12': '2'} having length is : 2
['l11', 'l22'] having length is : 2
Final Length
{'d11': '1', 'd12': '2'} having length is : 0
['l11', 'l22'] having length is : 0
有没有解决这个问题的好办法?谢谢!
您可以存储对列表本身的引用,并对其调用clear(),而不是存储列表的名称。
Result1={"d11":"1","d12":"2"}
Result2 =["l11","l22"]
def length(name):
print(str(name) + " having length is : "+ str(len(name)))
def GlobalClear():
overallList = [Result1, Result2]
for key in overallList:
key.clear()
print("Prev Length")
length(Result1)
length(Result2)
GlobalClear()
print("Final Length")
length(Result1)
length(Result2)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。