【问题标题】:Raising error if string not in one or more lists如果字符串不在一个或多个列表中,则引发错误
【发布时间】:2016-05-16 17:56:30
【问题描述】:

如果列表列表的一个或多个列表中没有出现target_string,我希望手动引发错误。

if False in [False for lst in lst_of_lsts if target_string not in lst]:
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

肯定有比上面指定的更 Pythonic 的解决方案。

【问题讨论】:

  • 请输入示例?
  • 您多久进行一次查找?

标签: python list boolean


【解决方案1】:

使用all()

if not all(target_string in lst for lst in lst_of_lsts):
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

生成器为每个单独的测试生成TrueFalseall() 检查它们是否都为真。由于我们使用的是生成器,因此评估是惰性的,即它会在找到第一个 False 而不评估完整列表时停止。

或者,如果同一标签上的双 in 看起来令人困惑,则可能

if not all((target_string in lst) for lst in lst_of_lsts):
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

但我不太确定这实际上会增加可读性。

【讨论】:

  • 就个人而言,我发现您的第一个解决方案比第二个解决方案更具可读性。不管怎样,答案都很好!
  • @MichaelGruenstaeudl 让我重新表述为“但您可能会发现......更具可读性,但这取决于个人喜好”;-)
【解决方案2】:

您可以通过以下方式保持惰性评估并增强易读性:

for lst in lst_of_lsts :
   if target_string not in lst : 
      raise ValueError('At least one  list does not contain "%s"' % (target_string))

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多