如何一起清除多个列表或字典

时间:2019-10-11 07:21:28

标签: python python-3.x list dictionary

我有大量的列表和字典,每次迭代都需要弄清楚。我试图编写一个函数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

请建议我采用合适的方法来解决上述问题。谢谢!

1 个答案:

答案 0 :(得分:2)

除了存储列表名称之外,您还可以存储对列表本身的引用,并在列表上调用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)

输出:

Prev Length
{'d11': '1', 'd12': '2'}  having length is : 2
['l11', 'l22']  having length is : 2
Final Length
{}  having length is : 0
[]  having length is : 0