惯用Python has_one

惯用Python has_one,第1张

概述我刚刚发明了一个愚蠢的小助手功能: def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ ite 我刚刚发明了一个愚蠢的小助手功能:

def has_one(seq,predicate=bool):    """Return whether there is exactly one item in `seq` that matches    `predicate`,with a minimum of evaluation (short-circuit).    """    iterator = (item for item in seq if predicate(item))    try:        iterator.next()    except stopiteration: # No items match predicate.        return False    try:        iterator.next()    except stopiteration: # Exactly one item matches predicate.        return True    return False # More than one item matches the predicate.

因为我能想到的最可读/惯用的内联事物是:

[predicate(item) for item in seq].count(True) == 1

…在我的情况下这很好,因为我知道seq很小,但它只是感觉很奇怪.有没有我在这里忘记的成语,这使我不得不打破这个助手?

澄清

回顾它,这是一个令人讨厌的问题,虽然我们得到了一些很好的答案!我正在寻找:

>一个明显的,可读的内联习语或stdlib函数,在这种情况下,急切的评估是可以接受的.
>一个更明显和可读的辅助函数 – 因为它打破了整个其他函数,只有最小量的评估似乎是可以接受的.

@Stephan202为辅助函数提出了一个非常酷的习语,@Martin v. Löwis在假设谓词返回bool的情况下提出了一个更简单的内联习语.感谢@大家的帮助!

解决方法 不确定它是否比你提出的版本更好,但是……

如果谓词仅保证返回True / False,那么

sum(map(predicate,seq)) == 1

会做(尽管它不会停在第二个元素)

总结

以上是内存溢出为你收集整理的惯用Python has_one全部内容,希望文章能够帮你解决惯用Python has_one所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1195251.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存