Python elegant assignment based on True/False values

后端 未结 11 1679
日久生厌
日久生厌 2021-01-31 09:32

I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a a         


        
11条回答
  •  渐次进展
    2021-01-31 09:58

    if your goal is to avoid writing a lot of "ands" and boolean expressions you can use prime number and only one conditions like this (example for 2 conditions)

     cond = (2**cond_1)*(3**cond_2)
    

    so

    cond == 1 #means cond_1 and cond_2 are False
    cond == 2 #means cond_1 is True and con_2 is False
    cond == 3 #means cond_1 is False and con_2 is True
    cond == 6 #means con_1 and Con_2 are True
    

    This hack can be used for 3 conditions using 3 primes and so on

    Like this...

    cond = (2**a)*(3**b)*(5**c)
    name = {30:'first', 6: 'second', 10:'third', 2:'fourth',
            15:'fifth', 3:'sixth', 5:'seventh', 1:'eighth'}[cond]
    

提交回复
热议问题