首页 > 解决方案 > 在理解列表中使用 next 而不是 break

问题描述

考虑一个词,我想在字典中搜索它,首先作为键,然后作为值。

我通过以下方式实现:

substitution_dict={'land':['build','construct','land'],
                   'develop':['develop', 'builder','land']}
word='land'
key = ''.join([next(key for key, value in substitution_dict.items() if word == key or word in value)])

这个想法是利用短路,单词首先与键进行比较,否则与值进行比较。但是,我想在找到密钥时停止。

运行上面的代码片段效果很好。但是,当word字典中不存在对其他单词的更改时,StopIteration由于下一个未找到结果的语句而引发错误。

我想知道这是否可以按照我的意图在一行中实现。

谢谢

标签: pythondictionarylist-comprehensionnext

解决方案


您可以在中传递一个默认参数next()next()并且只会返回一个元素,因此"".join([])是不必要的。

下面的代码:

key = next((key for key, value in substitution_dict.items() if word == key or word in value), None)

当迭代器用尽时,它会返回None

或者,如果您真的想将它与 一起使用''.join,例如:

key = "".join([next((key for key, value in substitution_dict.items() if word == key or word in value), "")])

推荐阅读