dict to boolean expression, how to?
Mark Lawrence
breamoreboy at yahoo.co.uk
Fri Aug 1 11:50:51 EDT 2014
On 01/08/2014 14:28, Steven D'Aprano wrote:
> On Fri, 01 Aug 2014 12:45:12 +0000, Alex van der Spek wrote:
>
>> With a dict like so:
>>
>> cond = {'a': 1, 'b': 1, 'c': 1,
>> 'A': 0, 'B', 0, 'C':0}
>>
>> how would you make a boolean expression like this:
>>
>> bool = (('a' == 1) & ('A' == 0) |
>> ('b' == 1) & ('B' == 0) |
>> ('c' == 1) & ('C' == 0))
>
> That's False. It's always False, because 'a' does not equal 1, etc. Also,
> you're using bitwise operators & and | rather than boolean operators.
> Finally, you are shadowing the built-in bool() type, which is probably a
> bad idea.
>
> In the first case, I think you mean cond['a'] == 1 rather than just
> 'a'==1; in the second case, the bool operators are called "and" and "or";
> and in the third case, there are many equally good names for a generic
> boolean flag, like "flag".
>
> Putting those together, I think you probably mean something like this:
>
> flag = (
> (cond['a'] == 1 and cond['A'] == 0) or
> (cond['b'] == 1 and cond['B'] == 0) or
> (cond['c'] == 1 and cond['C'] == 0)
> )
>
> which can be simplified to:
>
> flag = any( cond[c] == 1 and cond[c.upper()] for c in ['a', 'b', 'c'] )
>
Shouldn't that be cond[c.upper()] == 0 ?
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-list
mailing list