加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

惯用Python has_one

发布时间:2020-12-20 12:41:44 所属栏目:Python 来源:网络整理
导读:我刚刚发明了一个愚蠢的小助手功能: 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 predica
我刚刚发明了一个愚蠢的小助手功能:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读