为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据字典列表中另一个键的值获取一个键的最小值?

如何根据字典列表中另一个键的值获取一个键的最小值?

蓝山帝景 2023-09-26 16:42:55
我有一个字典列表,看起来像 -"produce": [    {        "name": "carrot",        "type": "vegetable",        "price": 10.0,        "units": "KG"    },    {        "name": "potato",        "type": "stem tuber",        "price": 2.0,        "units": "KG"    },    {        "type": "fruit",        "price": 5.0,        "units": "KG"    }]如果类型是水果或块茎,我需要获得最低的价格。我收到类型错误 -TypeError: 'float' object is not iterable我有以下代码 -for m in produce:    if ((m.get('type') == 'stem tuber') or         (m.get('type') == 'fruit')       ):       fPrice = min(m['price'])我收到错误fPrice = min(m['price'])。我不知道如何解决这个问题。有人可以帮忙吗?我需要获得5.0和之间的最低价格2.0,所以答案应该是2.0。
查看完整描述

2 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

您收到错误是因为您向 提供了单独的数字min(),并且min想要一个iterable诸如 a 的数字list。我们该如何解决这个问题?假设你有一本像这样的字典:


mydict = {"produce": [

    {

        "name": "carrot",

        "type": "vegetable",

        "price": 10.0,

        "units": "KG"

    },

    {

        "name": "potato",

        "type": "stem tuber",

        "price": 2.0,

        "units": "KG"

    },

    {

        "type": "fruit",

        "price": 5.0,

        "units": "KG"

    }

]}

produce = mydict['produce']

是时候构建列表理解了!

您想要迭代列表中的项目produce

[for m in produce]

然后,您想要检查该类型是否在某些字符串集中。

[for m in produce if m.get('type') in {'stem tuber', 'fruit'}]

然后,您想要提取其价格。如果不存在价格,则 0 似乎是合理的默认值!

[m.get('price', 0) for m in produce if m.get('type') in {'stem tuber', 'fruit'}]

然后你想找到最小值

min([m.get('price', 0) for m in produce if m.get('type') in {'stem tuber', 'fruit'}])

您还可以去掉周围的方括号m.get(...),它就成为一个生成器表达式

关于。 “如何处理列表理解中没有茎块茎或水果类型记录的情况”

您可以将另一个项目添加到列表中,如下所示:

min([m.get('price', 0) for m in produce if m.get('type') in {'stem tuber', 'fruit'}] + [-1])

据推测,没有任何成本为 -1(0 是最小值)。那么如果你得到-1,你就知道没有匹配的东西。


查看完整回答
反对 回复 2023-09-26
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您将单独的价格提供给min,这是行不通的。相反,提供可迭代的价格。您可以使用生成器表达式:

low = min(

    m['price']

    for m in produce

    if m.get('type') in {'stem tuber', 'fruit'}

    )

print(low)  # -> 2.0

如果它可以帮助您更好地理解,这就像使用列表理解然后将列表输入到min,但更直接。


prices = [

    m['price']

    for m in produce

    if m.get('type') in {'stem tuber', 'fruit'}

    ]

low = min(prices)

print(low)  # -> 2.0

要处理没有匹配价格的情况,请将min部分包装在try块中并使用except ValueError。举例来说,让我们使用现有数据,但假设您正在寻找葫芦的最低价格:


try:

    low = min(

        m['price']

        for m in produce

        if m.get('type') in {'gourd'}

        )

except ValueError:

    print('No matching prices')

    import sys

    sys.exit(1)


查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信