x = input("Color: ")
list = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
for mood in list: #???
print (mood["Mood"]) #???`如果我提示用户输入颜色,我希望它只在字典中打印与该颜色相关的“心情”。上面的for循环是我能想到的,但是不管用户输入哪种颜色,都会打印出所有的情绪--“愤怒”、“悲伤”、“狂热”。
我只是在学习,被困在使用"for“循环的地方。(我知道我可以为每种颜色/心情组合做几个布尔表达式,但我正在练习使用字典,所以这是首选的方法)。
发布于 2022-08-02 12:42:14
你真的应该改变你组织数据的方式。用颜色作为键,情绪作为项目计算字典:
l = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
moods = {d['Color']: d['Mood'] for d in l}
# {'Red': 'Angry', 'Blue': 'Sad', 'Green': 'Jealous'}然后,不需要循环:
print(moods.get(input('Color: '), 'unknown color!'))发布于 2022-08-02 12:51:44
好吧,让我们看看你的代码是怎么做的
x = input("Color: ")这要求用户提供颜色,并将其分配给变量"x“。
list = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]这就列出了三个单独的字典--一个有“颜色”“红色”和“情绪”“愤怒”,第二个有“颜色”“蓝色”和“心情”“悲伤”等等。
for mood in list: #???这将覆盖列表中的所有条目,因此每个循环都会运行循环变量"mood“,这将是上面的字典之一。
print (mood["Mood"]) #???`这将打印当前字典的“心情”值。
所以,您的问题是,您从来没有检查“颜色”是否是x!
最简单的解决方法可能是在for-循环中进行检查:
for item in list: # it's not a "mood", we have the full dictionary
if item["Color"] == x:
print(item["Mood"])
# if we know the color will only be in the list once,
# we can break out of the loop
break有更简洁的方法来做相同的事情,比如列表理解,这些方法可以在一行中执行for-循环所做的过滤,比如
moods = [ it["Mood"] for it in list if it["Color"] == x ]但这些都是更高级的话题。
您也可能只想以不同的方式组织数据,例如,您只需使用"Color“值作为字典键,并使用单个字典:
colors_to_moods = {
"Red": "Angry",
"Blue": "Sad",
"Green": "Jealous"
}
print(colors_to_moods[x])你想要使用哪一个取决于你想对你的程序做什么,否则。
发布于 2022-08-02 12:47:39
如果您想继续使用当前列表,可以测试x
x = input("Color: ")
color_to_mood = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
for c2m in color_to_mood:
if x == c2m['Color']:
print (c2m["Mood"])https://stackoverflow.com/questions/73207717
复制相似问题