📜  Python字典 clear()

📅  最后修改于: 2022-05-13 01:55:02.022000             🧑  作者: Mango

Python字典 clear()

clear() 方法从字典中删除所有项目。

句法:

dict.clear()

参数:

The clear() method doesn't take any parameters.

回报:

The clear() method doesn't return any value.

例子:

Input : d = {1: "geeks", 2: "for"}
        d.clear()
Output : d = {}

错误:

As we are not passing any parameters there
is no chance for any error.
# Python program to demonstrate working of
# dictionary clear()
text = {1: "geeks", 2: "for"}
  
text.clear()
print('text =', text)

输出:

text = {}

与将 {} 分配给字典有何不同?
请参阅下面的代码以查看差异。当我们将 {} 分配给字典时,会创建一个新的空字典并将其分配给引用。但是当我们清除字典引用时,实际的字典内容被删除,因此所有引用字典的引用都变为空。

# Python code to demonstrate difference
# clear and {}.
  
text1 = {1: "geeks", 2: "for"}
text2 = text1
  
# Using clear makes both text1 and text2
# empty.
text1.clear()
  
print('After removing items using clear()')
print('text1 =', text1)
print('text2 =', text2)
  
text1 = {1: "one", 2: "two"}
text2 = text1
  
# This makes only text1 empty.
text1 = {}
  
print('After removing items by assigning {}')
print('text1 =', text1)
print('text2 =', text2)

输出:

After removing items using clear()
text1 = {}
text2 = {}
After removing items by assigning {}
text1 = {}
text2 = {1: 'one', 2: 'two'}