【问题标题】:Using next instead of break in comprehension list在理解列表中使用 next 而不是 break
【发布时间】:2020-07-30 01:08:49
【问题描述】:

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

我是这样实现的:

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)])

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

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

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

谢谢

【问题讨论】:

  • 为什么要使用''.join()?您的列表中只有一个元素。
  • 我想从字典中的键或值中获取字符串。
  • 如果字典中没有这个词,究竟应该发生什么?为什么不正常捕获异常?

标签: python dictionary list-comprehension next


【解决方案1】:

您可以在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), "")])

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2017-01-26
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多