當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。