简体   繁体   English

为什么在 Python 中第二次输入后我的字典的值没有更新?

[英]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.

相关问题 如何在循环中将第二个值附加到字典中的现有键 - How to Append a 2nd value to an existing key in a dictionary in Python in a Loop 为什么第一个代码运行而第二个代码在定义后没有运行? - Why the 1st code runs and 2nd doesn't after defining it? Python:没有进入 For 循环的第二次迭代 - Python: Doesn't get to the 2nd iteration of For loop 为什么我的循环没有迭代列表中的第二个相同的值? - Why is my loop not iterating over the 2nd same value in the list? 如何在一行两个值输入后让用户输入第二个值? - How to have user input 2nd value after a one line two value input? 有没有办法更新 Python 字典的值,但如果它不存在则不添加键? - Is there a way to update the value of a Python dictionary but not add the key if it doesn't exist? 为什么我的python字典排序功能不起作用? - why my python dictionary sort function doesn't work? 嵌套的 for 循环在第二次迭代后停止并要求用户输入(在 python 代码中未使用输入 function) - The nested for loop stops after 2nd iteration and asks for user input (not used input function in the python code) Python'IF'之后的第二条语句没有动作 - Python No Action on 2nd Statement After 'IF' 我的while循环应该一直运行,直到用户想要停止它,但在第二次输入后结束 - My while loop should be running until the user wants to stop it but ends after the 2nd input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM