tjv*_*jvr 264 python dictionary idioms min minimum
如果我有一个Python字典,我如何获得包含最小值的条目的键?
我在考虑与这个min()功能有关...
鉴于输入:
{320:1, 321:0, 322:3}
Run Code Online (Sandbox Code Playgroud)
它会回来321.
Ale*_*lli 523
最佳:min(d, key=d.get)- 没有理由插入无用的lambda间接层或提取项目或密钥!
Mar*_*off 43
这是一个答案,实际上给出了OP要求的解决方案:
>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1])
(321, 0)
Run Code Online (Sandbox Code Playgroud)
d.iteritems()但是,对于较大的词典,使用将更有效.
jpp*_*jpp 27
对于具有相同最小值的多个键,您可以使用列表理解:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
Run Code Online (Sandbox Code Playgroud)
等效的功能版本:
res = list(filter(lambda x: d[x]==minval, d))
Run Code Online (Sandbox Code Playgroud)
min(zip(d.values(), d.keys()))[1]
Run Code Online (Sandbox Code Playgroud)
使用zip函数创建包含值和键的元组的迭代器。然后用 min 函数包装它,该函数根据第一个键取最小值。这将返回一个包含(值,键)对的元组。[1]的索引用于获取对应的key。
>>> d = {320:1, 321:0, 322:3}
>>> min(d, key=lambda k: d[k])
321
Run Code Online (Sandbox Code Playgroud)
对于您有多个最小键并希望保持简单的情况
def minimums(some_dict):
positions = [] # output variable
min_value = float("inf")
for k, v in some_dict.items():
if v == min_value:
positions.append(k)
if v < min_value:
min_value = v
positions = [] # output variable
positions.append(k)
return positions
minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})
['e', 'c']
Run Code Online (Sandbox Code Playgroud)