簡體   English   中英

Python3 pop() 函數只刪除字符串

[英]Python3 pop() function only deleting strings

我正在學習 Python 初學者課程,目前正在創建此示例字典:

dictVar = {25:"The square root of 5","Vitthal":"SOME DUDE'S NAME",3.14:"Pi"}

該課程正在教授如何使用交互式提示來請求字典中鍵的名稱,並將其分配給變量“inputKeyToDelete”

inputKeyToDelete = input("Please enter the key you wish to delete from the dictionary. Your key to delete is: ")

當我輸入鍵 Vitthal 時,鍵值對被刪除,但是當我輸入鍵 25 或 3.14 時,什么也沒有發生,這就是我提出問題的原因。

講師正在使用以下內容來執行查找\\刪除。

if inputKeyToDelete in dictVar:
    dictVar.pop(inputKeyToDelete)
    print("Ok, the key-value pair for Key '" + inputKeyToDelete + "' has been removed.")

任何提示表示贊賞。

input在python 3 中總是返回一個字符串。在python 中"25" != 25 ,所以找不到鍵。 您需要添加代碼來處理數字鍵。 這是一種方法:

inputKeyToDelete = input('enter a number:')
try:
    inputKeyToDelete = eval(inputKeyToDelete)
except NameError:
    pass

print (inputKeyToDelete)
print(type(inputKeyToDelete))

或者只是將您的示例更改為僅使用字符串鍵。

注意:在 python 2 中, input會為你轉換為整數,這可能會讓你有點困惑。

用下面的行替換您的代碼。 接受用戶輸入並將類型轉換為 int 因為 python 將字符串作為輸入。

inputKeyToDelete = int(input("Please enter the key you wish to delete from the dictionary. Your key to delete is: "))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM