在理解列表中使用 next 而不是 break

Using next instead of break in comprehension list

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

我是这样实现的:

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先和key比较,否则和value比较。但是,我想在密钥中找到时停止。

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

我想知道这是否可以像我预期的那样在一行中完成。

谢谢

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

代码如下:

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

当迭代器耗尽时,它会return None.

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

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