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

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

    This seems to work and should be able to handle any iterable, not justlists. It short-circuits whenever possible to maximize efficiency. Works in both Python 2 and 3.

    def only1(iterable):
        for i, x in enumerate(iterable):  # check each item in iterable
            if x: break                   # truthy value found
        else:
            return False                  # no truthy value found
        for x in iterable[i+1:]:          # one was found, see if there are any more
            if x: return False            #   found another...
        return True                       # only a single truthy value found
    
    testcases = [  # [[iterable, expected result], ... ]
        [[                          ], False],
        [[False, False, False, False], False],
        [[True,  False, False, False], True],
        [[False, True,  False, False], True],
        [[False, False, False, True],  True],
        [[True,  False, True,  False], False],
        [[True,  True,  True,  True],  False],
    ]
    
    for i, testcase in enumerate(testcases):
        correct = only1(testcase[0]) == testcase[1]
        print('only1(testcase[{}]): {}{}'.format(i, only1(testcase[0]),
                                                 '' if correct else
                                                 ', error given '+str(testcase[0])))
    

    Output:

    only1(testcase[0]): False
    only1(testcase[1]): False
    only1(testcase[2]): True
    only1(testcase[3]): True
    only1(testcase[4]): True
    only1(testcase[5]): False
    only1(testcase[6]): False
    

提交回复
热议问题