理解在字典中查找最小值 [英] Comprehension to find the min in a dict

查看:106
本文介绍了理解在字典中查找最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一件事情很好奇:

我有一个字典,例如以汽车为钥匙,并给出有关其速度的值.现在,我想找到具有最低值的密钥.

I have a dict, for example with a car as key and a value regarding its speed. Now, I want to find the key with the lowest value.

car_dict = {'mercedes': 200, 'fiat': 100, 'porsche': 300, 'rocketcar': 600}

我知道这段代码适用于O(1)

I know this code works with O(1)

car_value = list(car_dict.values())
car_key = list(car_dict.keys())
min_stats = min(car_value)
print(car_key[car_value.index(min_stats)]) 

这也是O(n)

keys = []
values = []
for name, value in car_dict.items():
    keys.append(name)
    values.append(value)

min_value = min(values)
print(keys[values.index(min_value)])

我目前正在尝试更好地理解理解,因此,我的问题是列表理解是否可以解决这个问题.

I am currently trying to better understand comprehensions, therefore, my question is if there would be a possible approach to this problem with list comprehensions.

我在想像这样的事情

worst = {name for name, stats in car_dict if min(stats)}

但是,我想我仍然误解了if部分中的某些内容.

However, I guess that I still misunderstand something in the if part.

如果我对上述Big O复杂性的看法有误,请纠正我.

BTW correct me if I am wrong with my belief in the Big O complexity above.

非常感谢!

推荐答案

我知道这段代码适用于O(1):

I know this code works with O(1):

car_value = list(car_dict.values())

这是不正确的.要从视图形成列表,您必须遍历所有值.此操作的时间复杂度为O(n).

This is incorrect. To form a list from a view you must iterate over all values. This operation will have time complexity of O(n).

通常,不需要创建键和值的列表.避免执行这些操作,因为它们很昂贵.

In general, creating a list of keys and values is not necessary. Avoid these operations as they are expensive.

请注意,min可以直接在dict.items上使用,这是键值对的视图.仅当您只有一辆具有最小值的汽车时才建议这样做:

Note that min can work directly on dict.items, which is a view of key-value pairs. This is only advisable if you only have a single car with the minimum value:

car, value = min(car_dict.items(), key=lambda x: x[1])  # (fiat, 100)

由于字典不被认为是有序的(除非您使用的是Python 3.7),对于重复的最小值,将无法确定结果.在这种情况下,您可以计算最小值,然后使用列表推导:

Since dictionaries are not considered ordered (unless you are using Python 3.7), for duplicate minima the result will not be certain. In this case, you can calculate the minimum value and then use a list comprehension:

min_val = min(car_dict.values())
min_cars = [car for car, value in car_dict.items() if value == min_val]  # ['fiat']

您还可以将next与生成器表达式一起使用,以提取第一辆这样的汽车:

You can also use next with a generator expression to extract the first such car:

min_car_first = next(car for car, value in car_dict.items() if value == min_val)

当然,如果是一辆具有最小值的汽车,其结果将与第一个解决方案min(car_dict.items(), ...)相同.

Of course, in the case of a single car with the minimum value, this will give the same result as the first solution min(car_dict.items(), ...).

这篇关于理解在字典中查找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆