开发者社区> 问答> 正文

如何清除多个列表或字典?

我有大量的列表和字典,它们需要在每次迭代中清除。我试图写一个函数的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

有没有解决这个问题的好办法?谢谢!

展开
收起
游客6qcs5bpxssri2 2019-10-11 16:32:41 2642 0
1 条回答
写回答
取消 提交回答
  • 您可以存储对列表本身的引用,并对其调用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)

    2019-10-11 16:33:58
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载