[英]Why doesn't the value of my dictionary update after 2nd input in Python?
I am trying to make a dictionary with the colour of cars as keys and the amount they are being input as the value, such that if "red" is input twice, the outcome would be "red cars: 2".我正在尝试使用汽车的颜色作为键和它们被输入的数量作为值制作一个字典,这样如果“红色”输入两次,结果将是“红色汽车:2”。 However, after if I input a colour more than twice, it won't update.
但是,如果我输入颜色两次以上,它就不会更新。
cars = {}
i = input("Cars: ")
value = 1
while i:
if i not in cars:
cars[i] = value
elif i in cars:
cars[i] = value + 1
i = input("Cars: ")
for i,value in sorted(cars.items()):
print(i + " cars: " + str(value))
If I input, ie, white 3 times, I get: white cars: 2
.如果我输入,即白色 3 次,我得到:
white cars: 2
。
Does anyone know what I'm doing wrong?有谁知道我做错了什么? Thanks in advance.
提前致谢。
用cars[i] += 1替换cars[i] = value + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.