How can I check that a list has one and only one truthy value?

后端 未结 17 2431
暗喜
暗喜 2020-11-27 12:23

In python, I have a list that should have one and only one truthy value (that is, bool(value) is True). Is there a clever way to check for this

17条回答
  •  清酒与你
    2020-11-27 13:12

    import collections
    
    def only_n(l, testval=True, n=1):
        counts = collections.Counter(l)
        return counts[testval] == n
    

    Linear time. Uses the built-in Counter class, which is what you should be using to check counts.

    Re-reading your question, it looks like you actually want to check that there is only one truthy value, rather than one True value. Try this:

    import collections
    
    def only_n(l, testval=True, coerce=bool, n=1):
        counts = collections.Counter((coerce(x) for x in l))
        return counts[testval] == n
    

    While you can get better best case performance, nothing has better worst-case performance. This is also short and easy to read.

    Here's a version optimised for best-case performance:

    import collections
    import itertools
    
    def only_n(l, testval=True, coerce=bool, n=1):
        counts = collections.Counter()
        def iterate_and_count():
            for x in itertools.imap(coerce,l):
                yield x
                if x == testval and counts[testval] > n:
                   break
        counts.update(iterate_and_count())
        return counts[testval] == n
    

    The worst case performance has a high k (as in O(kn+c)), but it is completely general.

    Here's an ideone to experiment with performance: http://ideone.com/ZRrv2m

提交回复
热议问题