当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Dictionary 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'}


相关用法


注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 Python Dictionary clear()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。