我刚开始学习Python,遇到了一个字典中的列表。
items_available = {
"orders": [1, 5, 10, 15, 20, 220, 330, 1000],
"grapes": {"green": 3, "purple": 7, "white": 1},
"litres_water": [1, 1.5, 2, 5, 10],
"bread": 27
}
我需要以某种方式分别获得葡萄部分的所有信息,我对如何做到这一点感到困惑。如。我事先确定了客户想要的葡萄数量和颜色。然后,我需要检查它是否从上述给定列表中可用。
我试着这样编码
amount_of_grape_packs_needed = order_details[3] # amount the customer is requesting. Found previously.
av_grapes = items_available.get('grapes')
max_available = amount_of_grape_packs_needed in av_grapesdesired_colour = order_details[2] in av_grapes
enough_packs = grape_amount_needed in max_available
? ?一片混乱。我知道。我还试着把葡萄从字典中提取出来作为一个列表然后只处理这个列表。但是我把事情搞砸了。
如有任何帮助,我将不胜感激。由于人(请原谅任何格式错误等,这是我第一次使用堆栈溢出:))
访问字典的keys()
和values()
,使用.items()
items_available = {
"orders": [1, 5, 10, 15, 20, 220, 330, 1000],
"grapes": {"green": 3, "purple": 7, "white": 1},
"litres_water": [1, 1.5, 2, 5, 10],
"bread": 27
}
for i,j in items_available['grapes'].items():
print(i,j)
列表形式:
[j for i in zip(items_available['grapes'].items()) for j in i]
如果我理解正确的话你要做的是
customer_grapes <= items_available['grapes']['green']
据我所知,这就是你想要做的。
用户输入所需的葡萄数(n
)和葡萄的颜色(color
)。
函数check()
检查用户订购的葡萄是否存在。
items_available = {
"orders": [1, 5, 10, 15, 20, 220, 330, 1000],
"grapes": {"green": 3, "purple": 7, "white": 1},
"litres_water": [1, 1.5, 2, 5, 10],
"bread": 27
}
def check(color, n):
data = items_available.get('grapes')
if data[color] >= n:
return f"Enough {color} grapes."
else:
return f"Not enough {color} grapes."
print(check('green',2))
print(check('white',4))
Enough green grapes.
Not enough white grapes.