python - 在理解列表中使用 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
由于下一个未找到结果的语句而引发错误。
我想知道这是否可以按照我的意图在一行中实现。
谢谢
解决方案
您可以在中传递一个默认参数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), "")])
推荐阅读
- c - GenerateConsoleCtrlEvent 不会关闭控制台应用程序
- google-sheets - 在 Google 表格中,您可以使用 WEEKNUM() 和 YEAR() 等特定条件计算行数吗?
- laravel - 使用 Laravel Horizon 进行动态配置
- r - 如何在 R 中将 05/02/1953 更改为 1953(即 dd/mm/yyyy 到 yyyy)?
- r - 使用 read.fortran 导入 .DAT 文件时出现错误
- azure - 无论如何将 Azure SQL 数据库从 VCORE 降级到 DTU 模型
- jquery - 使用 ajax 模拟表单提交行为
- batch-file - 将具有确切名称的多个文件夹移动到它自己的父文件夹
- html - 为 R Shiny UI 中的元素自定义单独的引导 CSS
- amazon-web-services - 如何将运行 Apache 的 Docker 容器绑定到域