[英]Little question/promblem about dictionary in Python
我正在為學校做作業,我需要將“月份”變量與字典(數字/月份名稱)進行比較,我嘗試使用.values()但是當我“啟動”不做任何事情的代碼時,謝謝對不起我的英語:]
Calendrier={1:"janvier",2:"février",3:"mars",4:"avril",5:"mai",6:'juin',
7:"juillet",8:"août",9:"septembre",10:"octobre",11:"novembre",12:"décembre"}
Volume=15500
Mois=1
Volume_Maximale=25000
while Volume<=Volume_Maximale:
Volume=Volume*0.9+2500
Mois=Mois+1
print("Le bassin débordera le mois de",Calendrier.values(Mois),"car il aura un volume de",Volume)
字典作為鍵訪問,所以只需輸入:
Calendrier[Mois]
起初在 python 中編程時有一些編碼約定,我會“糾正”你所做的一切“錯誤”(不是必須這樣做,但仍然建議這樣做)。
calendrier = (
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
)
volume = 15500
mois = 1
volume_maximale = 25000
while volume <= volume_maximale:
volume = volume*0.9+2500
mois = mois+1
# you have plenty possibilities to manipulate string
print("Le bassin débordera le mois de " + calendrier[mois-1] + " car il aura un volume de " + volume)
# if you are using pythoin 3.6 or later i would recommend the following
print(f"Le bassin débordera le mois de {calendrier[mois-1]} car il aura un volume de {volume}")
# its called f-string as you see you can directly write variables inside the string wrapped in curly braces
# for python 3.6 or later it is the fastes way manipulating strings
如您所見,我編輯了更多內容。 例如,您使用了幾個月的字典。 這絕對是合法的,但由於月份不會改變並且您不需要字典的功能,因此在這種情況下使用元組是一種更好的方法。 您也可以使用列表,但是由於元組是不可變的並且列表是不可變的,但是您不需要再次編輯列表,您應該使用元組。 但是有一個“缺點”; 變量“mois”現在需要從 0 開始,因為列表索引從 0 開始。因此,在訪問“calendrier”元組時,您需要從該變量中減去 1 以獲得正確的月份。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.