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

后端 未结 17 2427
暗喜
暗喜 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:13

    One that doesn't require imports:

    def single_true(iterable):
        i = iter(iterable)
        return any(i) and not any(i)
    

    Alternatively, perhaps a more readable version:

    def single_true(iterable):
        iterator = iter(iterable)
    
        # consume from "i" until first true or it's exhausted
        has_true = any(iterator) 
    
        # carry on consuming until another true value / exhausted
        has_another_true = any(iterator) 
    
        # True if exactly one true found
        return has_true and not has_another_true
    

    This:

    • Looks to make sure i has any true value
    • Keeps looking from that point in the iterable to make sure there is no other true value

提交回复
热议问题