I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this logical xor post and is trying to find a way to adapt to multiple variables and only one true.
Example
>>>TrueXor(1,0,0)
True
>>>TrueXor(0,0,1)
True
>>>TrueXor(1,1,0)
False
>>>TrueXor(0,0,0,0,0)
False
To check if a local variable exists in Python, use the in operator against the output of locals() function, which has a dictionary of a current local variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().
To check if multiple variables are not None: Wrap the variables in a sequence (e.g. a tuple or a list). Use the not in operator to check if None is not a member of the sequence. If the sequence doesn't contain None , then the variables are not None .
The equality operator ( == ) compares two variables for equality and returns True if they are equal. Otherwise, it returns False . Since a and b references the same object, they're both identical and equal.
There isn't one built in but it's not to hard to roll you own:
def TrueXor(*args):
return sum(args) == 1
Since "[b]ooleans are a subtype of plain integers" (source) you can sum the list of integers quite easily and you can also pass true booleans into this function as well.
So these two calls are homogeneous:
TrueXor(1, 0, 0)
TrueXor(True, False, False)
If you want explicit boolean conversion: sum( bool(x) for x in args ) == 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With