(Python)所以我设置了一个嵌套字典,如下所示:
{spanish word: {english word: .5, english word 2: .3, ...}}
其中键是西班牙语单词,值是嵌套字典,其键是英语单词及其概率。我想得到一个西班牙语单词,这样它就有了最大的价值。我试过(用目前的西班牙语单词)
maxenglish = max(d[word], key = d[word].get)
但这会返回英文单词。我对lambda函数不太熟悉,但我发现它可以使用吗?谢谢你的帮助!
编辑:转换英文和西班牙文
示例:
nesteddict = {"hola": {"hello":.5,"goodbye":.1}, "ciao": {"hello":.1,"goodbye":.5}
word = "hola"
argmax = max(nesteddict[word], key = nesteddict[word].get)
返回"hello“,但我希望它返回"hola”。
发布于 2022-03-20 05:05:30
这是你需要的东西吗?它需要字典和需要最合适翻译的单词。因此,它返回最适合的词,得到最大的分数。
def get_best_word(nesteddict, wd):
max_score = 0
key_with_max_score = ""
for k in nesteddict:
for sk in nesteddict[k]:
current_score = nesteddict[k][sk]
if sk == wd and current_score > max_score:
key_with_max_score = k
max_score = current_score
print(key_with_max_score)
也可以使用max函数将lambda函数作为参数传递给键max(nesteddict.keys(), key=lambda k: nesteddict[k]["hello"])
。
但是,如果所有嵌套字典中没有hello
键,则后者将引发一个错误。
https://stackoverflow.com/questions/71543963
复制相似问题