Python .values()[0] 提取字典中列表的第一个值

标签 python

我试图提取每个键的第一个值,但它似乎正在逐个迭代这些值,但不完全是我想要的,它正在这样做:

例如

    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/

相关文章:

python - Django 本地化消息合并错误

python - 生成所有 5 张牌扑克手

python - 如何使用 Python 确定 Google 日历中的当前事件?

python - 无法强制 puppeteer 点击 iframe 中的验证码

python - 将一个数组中的数组元素与另一个数组中的数组元素相除 - Python

python - Pandas:根据值对列进行分组并创建新的列标题

python - 如何使用 python 将下一个文本存储在 Telegram Bot 中

python - 你如何安装没有依赖项的python包

python - 类型错误 : object of type 'int' has no len() *subtraction*

python - 如果没有 GIL,则不允许来自 Python 的强制转换