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

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

    It depends if you are just looking for the value True or are also looking for other values that would evaluate to True logically (like 11 or "hello"). If the former:

    def only1(l):
        return l.count(True) == 1
    

    If the latter:

    def only1(l):
        return sum(bool(e) for e in l) == 1
    

    since this would do both the counting and the conversion in a single iteration without having to build a new list.

提交回复
热议问题