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

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

    You can do:

    x = [bool(i) for i in x]
    return x.count(True) == 1
    

    Or

    x = map(bool, x)
    return x.count(True) == 1
    

    Building on @JoranBeasley's method:

    sum(map(bool, x)) == 1
    

提交回复
热议问题