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

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

    Here's something that ought to work for anything truthy, though it has no short-circuit. I found it while looking for a clean way to forbid mutually-exclusive arguments:

    if sum(1 for item in somelist if item) != 1:
        raise ValueError("or whatever...")
    

提交回复
热议问题