Python elegant assignment based on True/False values

后端 未结 11 1611
日久生厌
日久生厌 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:42

    Another option would be to create a helper function:

    def first_true(*args):
        true_vals = (arg for arg in args if arg[0])
        return next(true_vals)[1]
    
    name = first_true((a and b and c, 'first'),
                      (a and b and not c, 'second'),
                      (a and not b and c, 'third'),
                      (a and not b and not c, 'fourth'),
                      (not a and b and c, 'fifth'),
                      (not a and b and not c, 'sixth'),
                      (not a and not b and c, 'seventh'),
                      (not a and not b and not c, 'eighth'))
    

    This method assumes that one of the tests passed in will be true. It could also be made lazier with lambdas.

提交回复
热议问题