我试图提取每个键的第一个值,但它似乎正在逐个迭代这些值,但不完全是我想要的,它正在这样做:
例如
def budget_options(self):
models = self.shop.get_bicycle_models()
for model, price in zip(self.shop.models.keys(), self.shop.models.values()[0]):
print(model, price)
if price * self.margin <= self.budget:
print("The {} is available for a price of ${:.2f}.".format(model, price * self.margin))
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] })
返回
('BMC Road Machine', 125)
The BMC Road Machine is available for a price of $150.00.
('Cannondale Synapse', 2)
The Cannondale Synapse is available for a price of $2.40.
什么时候应该
('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 类(class),试图学习,但目前我陷入困境。
最佳答案
你的字典没有顺序。这意味着当您调用 self.shop.models.keys()
和 self.shop.models.values()
时,值不一定会在与按键的顺序相同,导致您描述的意外行为。
这就是 dict.items()
的位置方法进来了。它的作用很简单:
Return a copy of the dictionary’s list of (key, value) pairs.
您可以在代码中使用它,如下所示:
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] })
当使用巨大的字典时,你应该使用 dict.iteritems()
反而。它的工作方式完全相同,但返回一个生成器,而不是在返回之前构建整个 (key, value)
对列表,从而减少内存使用。
关于Python .values()[0] 提取字典中列表的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709852/