简体   繁体   English

关于 Python 中字典的小问题/问题

[英]Little question/promblem about dictionary in Python

im doing a homework for school and i need to compare a variable of "months" with a dictionary (number/month name)i tried to use.values() but when i "launch" the code that don't do anything,thanks and sorry for my english:]我正在为学校做作业,我需要将“月份”变量与字典(数字/月份名称)进行比较,我尝试使用.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)

The dictionary is accessed as a key so just put:字典作为键访问,所以只需输入:

Calendrier[Mois]

At first there are some coding conventions when programming in python, I will 'correct' everything you did 'wrong' (it's not a must to do it so, but it's still recommended).起初在 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

As you can see I have edited some more things.如您所见,我编辑了更多内容。 For example you have used a dictionary for the months.例如,您使用了几个月的字典。 It is definitly legitement, but since the months don't changes and you dont need the functionality of an dictionary it is a better approach to use a tuple in this case.这绝对是合法的,但由于月份不会改变并且您不需要字典的功能,因此在这种情况下使用元组是一种更好的方法。 You could use a list too, but since tuples are immutable and lists are, but you don't need to edit the list again you should use a tuple.您也可以使用列表,但是由于元组是不可变的并且列表是不可变的,但是您不需要再次编辑列表,您应该使用元组。 But there is one "disadvantage";但是有一个“缺点”; the variable "mois" need to start at 0 now, because a list index starts at 0. Therefore you need to substract 1 from that variable to get the right month when accessing the "calendrier" tuple.变量“mois”现在需要从 0 开始,因为列表索引从 0 开始。因此,在访问“calendrier”元组时,您需要从该变量中减去 1 以获得正确的月份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM