Python.values()[0]来提取字典中列表的第一个值
我试图提取每个键的第一个值,但它似乎在一个接一个地迭代这些值,但并不完全是我想要的,它正在做: e、 g 应该是什么时候Python.values()[0]来提取字典中列表的第一个值,python,Python,我试图提取每个键的第一个值,但它似乎在一个接一个地迭代这些值,但并不完全是我想要的,它正在做: e、 g 应该是什么时候 ('BMC Road Machine', 125) The BMC Road Machine is available for a price of $150.00. ('Cannondale Synapse', 275) The Cannondale Synapse is available for a price of $330.00. 如果这是一个愚蠢的问题,我很抱歉
('BMC Road Machine', 125)
The BMC Road Machine is available for a price of $150.00.
('Cannondale Synapse', 275)
The Cannondale Synapse is available for a price of $330.00.
如果这是一个愚蠢的问题,我很抱歉,但我正在学习Thinkful Python课程,试图学习,但我现在陷入了困境。首先,不要使用
zip(models.keys(),models.values())
,而是使用models.items()
,它返回(key,values)
的元组
您可能对
值有更好的描述,但我不知道列表[125,2]
代表什么,除了第一项是价格这一事实。但这只是吹毛求疵。你的字典没有顺序。这意味着,当调用self.shop.models.keys()
和self.shop.models.values()
时,值不一定会以与键相同的顺序返回,从而导致您描述的意外行为
这就是该方法的用武之地。它的作用很简单:
返回字典(键、值)对列表的副本
您可以在代码中使用它,如下所示:
def budget_options(self):
models = self.shop.get_bicycle_models()
for model, prices in self.shop.models.items(): # Change this
price = prices[0] # Add this
print(model, price)
if price * self.margin <= self.budget:
print("The {} is available for a price of ${:.2f}.".format(model, price * self.
evans_cycles = BicycleShop("Evans Cycles", { "BMC Road Machine": [125, 2], "Cannondale Synapse": [275, 5], "Pinnacle Laterite": [450, 1], "Fuji Transonic": [625, 3], "Cervelo R2": [750, 5], "Specialized Roubaix": [999, 1] })
def预算_选项(自):
models=self.shop.get\u bicycle\u models()
对于模型,self.shop.models.items()中的价格:#更改此选项
价格=价格[0]#添加此项
打印(型号、价格)
如果price*self.margin,则字典没有顺序。元素的顺序可以在插入/删除/编辑时更改。不要将键和值压缩在一起,而是调用.items()
,您可以从中提取所有内容。相反,对于model,,price in self.shop.items():
非常漂亮,感谢您的清晰解释!
('BMC Road Machine', 125)
The BMC Road Machine is available for a price of $150.00.
('Cannondale Synapse', 275)
The Cannondale Synapse is available for a price of $330.00.
for model, values in self.shop.models.items():
price = values[0] # this is the first item you wanted
# do you stuff...
def budget_options(self):
models = self.shop.get_bicycle_models()
for model, prices in self.shop.models.items(): # Change this
price = prices[0] # Add this
print(model, price)
if price * self.margin <= self.budget:
print("The {} is available for a price of ${:.2f}.".format(model, price * self.
evans_cycles = BicycleShop("Evans Cycles", { "BMC Road Machine": [125, 2], "Cannondale Synapse": [275, 5], "Pinnacle Laterite": [450, 1], "Fuji Transonic": [625, 3], "Cervelo R2": [750, 5], "Specialized Roubaix": [999, 1] })