Python字典 - 找到产生最小值的2个字符的字符串中的第二个字符 [英] Python dictionaries - find second character in a 2-character string which yields minimum value

查看:209
本文介绍了Python字典 - 找到产生最小值的2个字符的字符串中的第二个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提交一个键的第一部分,并返回该键的剩余部分,最小化该值(从第一部分开始)。

I would like to submit the first part of a key and return the remaining part of that key which minimizes the value (and starts with the first part).

例如:

d = {'ab': 100,
     'ac': 200,
     'ad': 500}

如果我要通过我想返回'b'`。

If I were to pass in 'a', I would like to return'b'`.

推荐答案

min(((d[s],s) for s in d if s.startswith('a')))[1][1:]

min (value)中找到最小 ,键)对,然后我们拿钥匙(最小值),并显示它的后半部分。这使用 min 的事实,最小化了一个元组中的第一个值。

The min finds the minimum value in the (value, key) pairs, and then we take the key (with the smallest value), and display the latter part of it. This uses the fact that min, minimises over the first value in a tuple.

我们可以概括为找到以字符串开头 a 的最小值:

And we could generalise to find the minimum which "starts with a string" a as:

def smallest_value_of_key_startswith(a, d):
    min(((d[s],s) for s in d if s.startswith(a)))[1][len(a):]

这篇关于Python字典 - 找到产生最小值的2个字符的字符串中的第二个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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